Introduction To Python

Expert-defined terms from the Python Programming Fundamentals course at Stanmore School of Business. Free to read, free to share, paired with a professional course.

Introduction To Python

Variable #

Variable – a named location in memory that holds a value. Related terms: identifier, assignment, data type. Explanation: Variables allow programs to store and retrieve data dynamically. Example: age = 25 stores the integer 25 in the variable named age. Practical application: Tracking user input such as scores or settings. Challenge: Predicting the effect of changing a variable’s type during execution.

Constant #

Constant – a value that should not change after its definition. Related terms: Immutable, literal, naming convention. Explanation: Python does not enforce constants, but naming in uppercase signals intent. Example: MAX_USERS = 100. Practical application: Defining limits like buffer sizes or API keys. Challenge: Ensuring code respects the constant convention in large teams.

Data type #

Data type – classification of values that determines the operations permitted on them. Related terms: int, float, str, bool. Explanation: Python provides built‑in types such as integers, floating‑point numbers, strings, and booleans. Example: Type(3.14) Returns float. Practical application: Choosing the appropriate type for calculations, text handling, or logical decisions. Challenge: Converting between types without losing precision or causing errors.

Integer #

Integer – a whole number without a fractional component. Related terms: int, arithmetic, overflow. Explanation: Python’s int type has arbitrary precision, so it can represent very large numbers. Example: count = 42. Practical application: Counting items, indexing lists, or representing IDs. Challenge: Managing performance when working with extremely large integers.

Floating‑point #

Floating‑point – a number that includes a decimal point. Related terms: float, rounding, precision. Explanation: Floats approximate real numbers, but limited binary representation can cause small errors. Example: price = 19.99. Practical application: Monetary calculations, scientific measurements. Challenge: Avoiding rounding errors in financial applications; use the decimal module when needed.

String #

String – a sequence of Unicode characters. Related terms: str, concatenation, slicing. Explanation: Strings are immutable; operations produce new string objects. Example: Greeting = "Hello, " + "world!". Practical application: Displaying messages, parsing input, generating file paths. Challenge: Handling different encodings and escaping special characters.

Boolean #

Boolean – a logical value representing true or false. Related terms: bool, truthiness, conditional. Explanation: Booleans are often the result of comparison operators. Example: Is_valid = (score >= 60). Practical application: Controlling flow with if‑else statements. Challenge: Understanding truthy vs falsy values in complex expressions.

List #

List – an ordered, mutable collection of items. Related terms: append, index, slice. Explanation: Lists can hold heterogeneous types and are commonly used for sequences. Example: Fruits = ["apple", "banana", "cherry"]; fruits.Append("date"). Practical application: Storing records, building queues, aggregating results. Challenge: Managing large lists efficiently; consider using generators or array modules.

Tuple #

Tuple – an ordered, immutable collection of items. Related terms: unpack, immutable, namedtuple. Explanation: Tuples provide read‑only sequence semantics and can be used as dictionary keys. Example: Point = (3, 5). Practical application: Representing fixed‑size records such as coordinates. Challenge: Deciding when immutability is beneficial versus the flexibility of lists.

Dictionary #

Dictionary – a collection of key‑value pairs with fast lookup. Related terms: hash, key, value, update. Explanation: Keys must be hashable; values can be any type. Example: Student = {"name": "Alice", "id": 12345}. Practical application: Storing configuration options, JSON‑like data structures. Challenge: Avoiding key collisions and handling missing keys gracefully.

Set #

Set – an unordered collection of unique items. Related terms: union, intersection, frozenset. Explanation: Sets automatically discard duplicates and support mathematical operations. Example: Primes = {2, 3, 5, 7}; primes.Add(11). Practical application: De‑duplicating data, membership testing. Challenge: Remembering that sets are unordered; cannot index directly.

None #

None – a special constant representing the absence of a value. Related terms: Null, nil, sentinel. Explanation: None is often used as a default argument or to indicate “no result”. Example: Result = None. Practical application: Signaling optional data, end‑of‑file markers. Challenge: Distinguishing between None and falsy values like 0 or empty strings.

Operator #

Operator – a symbol that performs a computation on one or more operands. Related terms: Arithmetic, logical, comparison. Explanation: Python supports +, -, *, /, //, %, **, and more. Example: Total = a + b. Practical application: Calculating totals, comparing values, building expressions. Challenge: Understanding operator precedence and short‑circuit behavior.

Expression #

Expression – a combination of values, variables, and operators that yields a result. Related terms: Statement, evaluation, syntax. Explanation: Expressions can be nested and are evaluated according to precedence rules. Example: Result = (x * 2) + (y / 3). Practical application: Computing derived data inside assignments or function arguments. Challenge: Writing readable complex expressions without excessive nesting.

Statement #

Statement – a syntactic unit that performs an action. Related terms: Expression, control flow, block. Explanation: Examples include assignment, import, return, and control structures. Example: print("Hello"). Practical application: Directing program execution, calling functions, handling I/O. Challenge: Differentiating between statements that produce values and those that do not.

Function #

Function – a reusable block of code that performs a specific task. Related terms: def, parameter, return value. Explanation: Functions promote modularity and avoid duplication. Example: Def add(a, b): Return a + b. Practical application: Encapsulating calculations, API endpoints, data transformations. Challenge: Designing clear signatures and handling optional parameters.

Method #

Method – a function that is bound to an object and operates on its data. Related terms: Object‑oriented, self, attribute. Explanation: Methods are accessed via dot notation on instances. Example: My_list.Append(10). Practical application: Manipulating collections, performing I/O on file objects. Challenge: Understanding the difference between class methods, static methods, and instance methods.

Class #

Class – a blueprint for creating objects with shared attributes and methods. Related terms: object, inheritance, encapsulation. Explanation: Classes define the structure and behavior of their instances. Example: Class Person: Def __init__(self, name): Self.Name = name. Practical application: Modeling real‑world entities, building reusable components. Challenge: Designing class hierarchies that avoid tight coupling and redundancy.

Object #

Object – an instance of a class containing state and behavior. Related terms: instance, attribute, method. Explanation: Objects encapsulate data and provide methods to interact with that data. Example: Alice = Person("Alice"). Practical application: Managing complex data structures, implementing GUI widgets. Challenge: Controlling object lifecycle and memory usage in long‑running programs.

Inheritance #

Inheritance – a mechanism where a class derives attributes and methods from another class. Related terms: Superclass, subclass, super. Explanation: Enables code reuse and polymorphic behavior. Example: Class Employee(Person): Pass. Practical application: Extending base functionality for specialized roles. Challenge: Avoiding deep inheritance trees that become hard to maintain.

Polymorphism #

Polymorphism – the ability of different objects to be accessed through the same interface. Related terms: Duck typing, method overriding, abstraction. Explanation: In Python, polymorphism often relies on shared method names rather than strict type hierarchies. Example: Both list and tuple support the len function. Practical application: Writing generic algorithms that operate on any iterable. Challenge: Ensuring that assumed methods exist on all accepted types.

Encapsulation #

Encapsulation – the bundling of data with the methods that manipulate that data. Related terms: Private attribute, getter, setter. Explanation: Python uses naming conventions (single or double underscore) to indicate private members. Example: Self.__Balance = 0. Practical application: Hiding internal state, providing controlled access via properties. Challenge: Balancing accessibility with protection; over‑encapsulation can hinder testing.

Module #

Module – a file containing Python definitions and statements intended for reuse. Related terms: Import, package, namespace. Explanation: Modules provide a way to organize code into logical units. Example: Import math; math.Sqrt(9). Practical application: Sharing utility functions across multiple scripts. Challenge: Managing circular imports and version compatibility.

Package #

Package – a directory containing a collection of modules and an __init__.Py file. Related terms: Distribution, pip, virtual environment. Explanation: Packages enable hierarchical organization of related modules. Example: From urllib import request. Practical application: Distributing libraries, structuring large applications. Challenge: Maintaining consistent __init__ behavior and avoiding namespace clashes.

Import #

Import – a statement that brings a module or specific attributes into the current namespace. Related terms: From…import, alias, __all__. Explanation: Importing can be absolute or relative. Example: From datetime import datetime as dt. Practical application: Accessing standard library functions, third‑party tools. Challenge: Preventing name collisions and minimizing import overhead.

Namespace #

Namespace – a mapping from names to objects, defining the scope in which identifiers are resolved. Related terms: Global, local, built‑ins. Explanation: Each module, function, and class creates its own namespace. Example: The variable x inside a function does not affect x in the global scope. Practical application: Isolating variables to avoid unintended side effects. Challenge: Debugging name resolution errors in nested scopes.

Scope #

Scope – the region of a program where a name is valid. Related terms: Lexical, dynamic, closure. Explanation: Python primarily uses lexical (static) scoping. Example: Variables defined inside a function are local to that function. Practical application: Controlling variable visibility, reducing side effects. Challenge: Understanding the interaction of global and nonlocal declarations.

Closure #

Closure – a function object that retains access to variables from its defining environment. Related terms: Lambda, nested function, free variable. Explanation: Closures enable data to persist without using global state. Example: Def make_adder(n): Def adder(x): Return x + n; return adder. Practical application: Creating factories, decorators, and callbacks. Challenge: Managing mutable free variables and avoiding unexpected state sharing.

Lambda #

Lambda – an anonymous function defined with the lambda keyword. Related terms: Functional programming, map, filter. Explanation: Lambdas are limited to a single expression. Example: Squares = list(map(lambda x: X*x, range(5))). Practical application: Short‑hand transformations in higher‑order functions. Challenge: Maintaining readability when overusing complex lambda expressions.

Decorator #

Decorator – a callable that modifies another function or method. Related terms: @Syntax, wrapper, functools.Wraps. Explanation: Decorators are applied using the @ symbol above a function definition. Example: @Staticmethod def helper(): Pass. Practical application: Adding logging, access control, or memoization without altering core logic. Challenge: Preserving function metadata and handling arguments correctly.

Generator #

Generator – a function that yields values one at a time, producing an iterator. Related terms: Yield, iterator, lazy evaluation. Explanation: Generators maintain state between yields, allowing efficient memory usage. Example: Def count_up(n): I = 0; while i < n: Yield i; i += 1. Practical application: Streaming large datasets, implementing infinite sequences. Challenge: Managing generator exhaustion and ensuring proper cleanup.

Iterator #

Iterator – an object that implements the __next__ method and returns successive items. Related terms: Iterable, for‑loop, StopIteration. Explanation: Iterators provide a uniform way to traverse collections. Example: It = iter([1, 2, 3]); next(it) → 1. Practical application: Custom data pipelines, lazy computation. Challenge: Designing robust __next__ methods that correctly signal termination.

Iterable #

Iterable – an object capable of returning an iterator via the __iter__ method. Related terms: Sequence, collection, generator. Explanation: All built‑in containers like list, tuple, dict, and set are iterables. Example: For item in "hello": Print(item). Practical application: Enabling generic loops over custom data structures. Challenge: Ensuring __iter__ returns a fresh iterator each time.

Comprehension #

Comprehension – a concise syntax for creating lists, sets, or dictionaries from existing iterables. Related terms: List comprehension, set comprehension, dict comprehension. Explanation: Comprehensions embed loops and conditionals inside a single expression. Example: Evens = [x for x in range(10) if x % 2 == 0]. Practical application: Transforming data, filtering collections, building mappings. Challenge: Avoiding overly complex comprehensions that reduce readability.

Exception #

Exception – an error condition that disrupts normal flow and can be caught with try‑except blocks. Related terms: Raise, traceback, finally. Explanation: Python distinguishes between built‑in exceptions and user‑defined ones. Example: Try: Int("abc") except ValueError as e: Print(e). Practical application: Graceful handling of invalid input, file I/O errors, network failures. Challenge: Writing precise exception hierarchies and avoiding blanket except clauses.

Try‑except #

Try‑except – a construct for catching and handling exceptions. Related terms: Finally, else, raise. Explanation: Code in the try block is monitored; matching except blocks handle specific errors. Example: Try: F = open("data.Txt") except FileNotFoundError: Print("Missing file"). Practical application: Robust user interfaces that recover from runtime issues. Challenge: Determining the appropriate granularity of exception handling.

Finally #

Finally – a clause that executes after try‑except, regardless of whether an exception occurred. Related terms: Cleanup, context manager, with. Explanation: Commonly used to release resources such as files or locks. Example: Try: F = open("log.Txt") finally: F.Close(). Practical application: Ensuring deterministic release of external resources. Challenge: Managing nested finally blocks and avoiding suppressed exceptions.

Raise #

Raise – a statement that triggers an exception deliberately. Related terms: Custom exception, error handling, traceback. Explanation: Raising propagates the error up the call stack unless caught. Example: If score < 0: Raise ValueError("Score cannot be negative"). Practical application: Validating function arguments, enforcing invariants. Challenge: Choosing the most specific exception type to aid debugging.

Assertion #

Assertion – a statement that checks a condition and raises an AssertionError if false. Related terms: Debug, test, assert. Explanation: Assertions are intended for development; they can be disabled with the -O flag. Example: Assert len(items) > 0, "List must not be empty". Practical application: Documenting assumptions, catching programming errors early. Challenge: Not using assertions for runtime validation of user data.

File I/O #

File I/O – operations for reading from and writing to files on disk. Related terms: Open, read, write, with. Explanation: Files are opened in specific modes (r, w, a, b) and should be closed after use. Example: With open("output.Txt", "w") as f: F.Write("Hello"). Practical application: Persisting data, logging, configuration management. Challenge: Handling encoding issues, large files, and concurrent access.

Context manager #

Context manager – an object that defines __enter__ and __exit__ methods for resource management. Related terms: With statement, __enter__, __exit__. Explanation: The with statement automatically invokes these methods, ensuring proper setup and teardown. Example: With open("data.Csv") as f: For line in f: Print(line). Practical application: Managing files, network connections, threading locks. Challenge: Implementing custom context managers that correctly propagate exceptions.

With statement #

With statement – a syntactic construct that simplifies the use of context managers. Related terms: Context manager, resource, __exit__. Explanation: It guarantees that cleanup code runs even if an error occurs. Example: With threading.Lock() as lock: Lock.Acquire(). Practical application: Reducing boilerplate for safe resource handling. Challenge: Understanding the difference between using a lock as a context manager versus explicit acquire/release.

Thread #

Thread – a lightweight flow of execution within a process. Related terms: Concurrency, threading, GIL. Explanation: Python’s threading module provides a high‑level interface for spawning threads. Example: T = threading.Thread(target=worker); t.Start(). Practical application: Performing I/O‑bound tasks concurrently. Challenge: Dealing with the Global Interpreter Lock (GIL) and race conditions.

Process #

Process – an independent execution environment with its own memory space. Related terms: Multiprocessing, fork, spawn. Explanation: The multiprocessing module creates separate processes to bypass the GIL. Example: P = multiprocessing.Process(target=compute); p.Start(). Practical application: Parallelizing CPU‑intensive workloads. Challenge: Managing inter‑process communication and shared resources.

Lock #

Lock – a synchronization primitive that ensures exclusive access to a resource. Related terms: Threading.Lock, mutex, deadlock. Explanation: Acquiring a lock blocks other threads until it is released. Example: Lock.Acquire(); critical_section(); lock.Release(). Practical application: Protecting shared data structures from concurrent modification. Challenge: Avoiding deadlocks by ordering lock acquisition consistently.

Queue #

Queue – a thread‑safe data structure for passing messages between producer and consumer threads. Related terms: Deque, multiprocessing.Queue, FIFO. Explanation: The queue module provides Queue, LifoQueue, and PriorityQueue classes. Example: Q = queue.Queue(); q.Put(item); q.Get(). Practical application: Implementing pipelines, task scheduling. Challenge: Handling full or empty queues without blocking indefinitely.

Regular expression #

Regular expression – a pattern describing a set of strings, used for searching and manipulation. Related terms: Re module, pattern, match. Explanation: Python’s re library supports compilation of patterns for efficiency. Example: Re.Search(r"\d+", "abc123") returns a match object. Practical application: Validating input formats, extracting data from logs. Challenge: Writing readable patterns and avoiding catastrophic backtracking.

JSON #

JSON – JavaScript Object Notation, a lightweight data‑interchange format. Related terms: Json module, serialize, deserialize. Explanation: Python can convert between native data structures and JSON strings. Example: Data = json.Loads('{"name":"Bob"}'); json_str = json.Dumps(data). Practical application: Communicating with web APIs, storing configuration. Challenge: Handling non‑serializable objects and preserving type information.

Pickle #

Pickle – a Python‑specific serialization format for arbitrary objects. Related terms: Pickle module, dump, load. Explanation: Pickle can serialize complex objects but is not secure against untrusted data. Example: With open("obj.Pkl", "wb") as f: Pickle.Dump(my_obj, f). Practical application: Caching computational results, saving program state. Challenge: Maintaining compatibility across Python versions and avoiding security risks.

Virtual environment #

Virtual environment – an isolated Python environment with its own site‑packages directory. Related terms: Venv, pip, dependency management. Explanation: Venv creates a directory that contains the interpreter, libraries, and scripts. Example: Python -m venv env; source env/bin/activate. Practical application: Preventing package version conflicts between projects. Challenge: Remembering to activate the environment before installing dependencies.

Package manager #

Package manager – a tool that installs, updates, and removes Python packages. Related terms: Pip, PyPI, requirements.Txt. Explanation: Pip interacts with the Python Package Index to retrieve distributions. Example: Pip install requests==2.28.0. Practical application: Adding third‑party libraries such as NumPy or Flask. Challenge: Resolving dependency conflicts and ensuring reproducible builds.

PEP #

PEP – Python Enhancement Proposal, a design document describing new features or standards. Related terms: PEP 8, PEP 20, community. Explanation: PEPs are reviewed and accepted by the core development team. Example: PEP 8 defines the official style guide for Python code. Practical application: Guiding code style, contributing to language evolution. Challenge: Keeping up with changes and applying them consistently.

Docstring #

Docstring – a string literal that appears as the first statement in a module, class, or function. Related terms: __Doc__, help, Sphinx. Explanation: Docstrings provide documentation that can be accessed at runtime. Example: Def add(a, b): """Return the sum of a and b.""" Return a + b. Practical application: Generating API documentation, enabling interactive help. Challenge: Writing comprehensive yet concise docstrings for complex functions.

Type hint #

Type hint – an optional annotation that specifies the expected type of a variable or function parameter. Related terms: Typing module, static analysis, mypy. Explanation: Hints do not enforce types at runtime but assist tooling. Example: Def greet(name: Str) -> str: Return f"Hello, {name}". Practical application: Improving code readability and catching type errors early. Challenge: Maintaining accurate hints as the code evolves.

Interpreter #

Interpreter – the program that reads and executes Python code line by line. Related terms: REPL, CPython, PyPy. Explanation: The standard interpreter, CPython, compiles source to bytecode before execution. Example: Running python script.Py invokes the interpreter. Practical application: Rapid prototyping, debugging interactive sessions. Challenge: Understanding performance differences between interpreters.

Bytecode #

Bytecode – a low‑level, platform‑independent representation of Python source code. Related terms: .Pyc files, compile, virtual machine. Explanation: The interpreter translates source to bytecode, which the Python virtual machine executes. Example: Import py_compile; py_compile.Compile('module.Py'). Practical application: Reducing startup time for large applications. Challenge: Debugging issues that arise only after compilation.

Garbage collection #

Garbage collection – the automatic reclamation of memory that is no longer reachable. Related terms: Reference counting, cyclic garbage, gc module. Explanation: CPython primarily uses reference counting, supplemented by a cyclic collector. Example: Import gc; gc.Collect(). Practical application: Preventing memory leaks in long‑running programs. Challenge: Identifying and breaking reference cycles that the collector cannot resolve.

Reference count #

Reference count – the number of references pointing to an object. Related terms: Refcount, gc, weakref. Explanation: When the count drops to zero, the object is immediately deallocated. Example: Sys.Getrefcount(obj) returns the current count. Practical application: Understanding object lifetimes and optimizing memory usage. Challenge: Dealing with temporary increases in count during debugging.

Weak reference #

Weak reference – a reference that does not increase an object’s reference count. Related terms: Weakref module, finalizer, cache. Explanation: Weak references allow objects to be reclaimed while still being tracked. Example: Ref = weakref.Ref(obj); ref() returns the object if still alive. Practical application: Implementing memoization caches that do not prevent garbage collection. Challenge: Handling the case where the referenced object has been collected.

Metaclass #

Metaclass – a class of a class; it defines how classes behave. Related terms: Type, class creation, __new__. Explanation: By default, Python classes are instances of the built‑in type metaclass. Example: Class MyMeta(type): Def __new__(mcls, name, bases, attrs): Return super().__New__(mcls, name, bases, attrs). Practical application: Enforcing coding standards, automatically registering subclasses. Challenge: Writing metaclasses that remain compatible with multiple inheritance hierarchies.

Descriptor #

Descriptor – an object that defines __get__, __set__, or __delete__ to manage attribute access. Related terms: Property, data descriptor, non‑data descriptor. Explanation: Descriptors are the underlying mechanism of @property and other attribute protocols. Example: Class Celsius: Def __init__(self, temperature): Self._Temp = temperature; def __get__(self, instance, owner): Return self._Temp. Practical application: Validating assignments, computing derived attributes on demand. Challenge: Correctly handling owner and instance arguments in complex inheritance scenarios.

Property #

Property – a built‑in descriptor that provides controlled access to an attribute via getter, setter, and deleter. Related terms: @Property, attribute, encapsulation. Explanation: Using @property allows method calls to appear as attribute accesses. Example: @Property def area(self): Return self.Width * self.Height. Practical application: Maintaining backward compatibility while refactoring internal implementation. Challenge: Preventing infinite recursion when the getter or setter accesses the same property.

Iterator protocol #

Iterator protocol – the set of methods (__iter__ and __next__) that an object must implement to be iterable. Related terms: Iterable, generator, StopIteration. Explanation: The protocol enables Python’s for‑loop to retrieve items lazily. Example: Class Counter: Def __iter__(self): Return self; def __next__(self): ... Practical application: Creating custom data streams such as reading lines from a network socket. Challenge: Ensuring that __next__ raises StopIteration at the appropriate time.

File object #

File object – an object returned by open that provides methods for reading and writing. Related terms: Read, write, seek, mode. Explanation: File objects support iteration over lines and can be used as context managers. Example: With open("log.Txt", "r") as f: For line in f: Process(line). Practical application: Processing large text files without loading them entirely into memory. Challenge: Handling binary vs text modes and platform‑specific newline conventions.

Encoding #

Encoding – the transformation of characters into a sequence of bytes. Related terms: UTF‑8, Unicode, decode, encode. Explanation: Python strings are Unicode; encoding is required when interfacing with external byte streams. Example: B = "café".Encode("utf-8"); s = b.Decode("utf-8"). Practical application: Reading international text files, communicating over network protocols. Challenge: Detecting and converting between unknown encodings without data loss.

Standard library #

Standard library – the collection of modules that ship with Python, providing common functionality. Related terms: Os, sys, datetime, itertools. Explanation: It offers tools for file handling, networking, data processing, and more. Example: Import datetime; datetime.Datetime.Now(). Practical application: Reducing external dependencies by leveraging built‑in modules. Challenge: Discovering appropriate modules among the extensive library.

Third‑party library #

Third‑party library – a package developed outside the Python core distribution. Related terms: Pip, PyPI, dependency. Explanation: Libraries such as NumPy, Requests, and Django extend Python’s capabilities. Example: Import requests; response = requests.Get("https://Api.Example.Com"). Practical application: Adding specialized functionality like scientific computing or web frameworks. Challenge: Managing version compatibility and security updates.

Virtualenv #

Virtualenv – a tool that creates isolated Python environments, similar to venv but with additional features. Related terms: Site‑packages, activation, pip. Explanation: Virtualenv can be used with older Python versions lacking the built‑in venv module. Example: Virtualenv myenv; source myenv/bin/activate. Practical application: Consistent development setups across diverse machines. Challenge: Keeping the virtual environment synchronized with the system interpreter after upgrades.

Package index #

Package index – a repository of Python packages, the most common being the Python Package Index (PyPI). Related terms: Pip install, distribution, wheel. Explanation: Packages are uploaded as source distributions or binary wheels for easy installation. Example: Pip install numpy – pulls the package from PyPI. Practical application: Distributing reusable code to the broader community. Challenge: Verifying package integrity and avoiding supply‑chain attacks.

Wheel #

Wheel – a built‑distribution format for Python packages that speeds up installation. Related terms: .Whl, binary distribution, pip. Explanation: Wheels contain pre‑compiled code and metadata, eliminating the need for source compilation. Example: Pip install pandas‑1.5.0‑Cp39‑cp39‑win_amd64.Whl. Practical application: Deploying packages on platforms without compilers. Challenge: Ensuring wheel compatibility with the target Python version and architecture.

Namespace package #

Namespace package – a package that can be split across multiple directories or distributions. Related terms: Pkgutil, importlib, split‑install. Explanation: Namespace packages lack an __init__.Py file, allowing separate projects to contribute subpackages. Example: Import mycompany.Utils; import mycompany.Services. Practical application: Organizing large codebases across multiple repositories. Challenge: Configuring packaging tools to correctly declare namespace packages.

Setup script #

Setup script – a Python script named setup.Py that defines how a package is built and installed. Related terms: Setuptools, distutils, install_requires. Explanation: The script specifies metadata, dependencies, and entry points for the package. Example: From setuptools import setup; setup(name="mytool", version="0.1", Packages=["mytool"]). Practical application: Publishing a library to PyPI. Challenge: Migrating to modern standards such as pyproject.Toml while maintaining backward compatibility.

Pyproject.Toml #

Pyproject.Toml – a configuration file that defines build system requirements and metadata for Python projects. Related terms: PEP 517, PEP 518, build backend. Explanation: Tools like poetry and flit read this file to manage dependencies and packaging. Example: [Build-system] requires = ["setuptools>=42", "wheel"]; build-backend = "setuptools.Build_meta". Practical application: Standardizing project configuration across diverse tooling ecosystems. Challenge: Understanding which fields are required for different build backends.

ImportError #

ImportError – an exception raised when an import statement fails to locate a module. Related terms: ModuleNotFoundError, traceback, sys.Path. Explanation: ImportError provides details about the missing module or attribute. Example: Try: Import nonexistent; except ImportError as e: Print(e). Practical application: Providing fallback implementations when optional dependencies are unavailable. Challenge: Diagnosing path‑related issues in complex virtual environments.

ModuleNotFoundError #

ModuleNotFoundError – a subclass of ImportError indicating that a module cannot be found. Related terms: Import, exception hierarchy, pip. Explanation: Raised when the import machinery cannot locate the specified module. Example: Import pandas; # raises ModuleNotFoundError if pandas is not installed. Practical application: Prompting users to install missing packages. Challenge: Distinguishing between missing top‑level packages and submodule import failures.

SyntaxError #

SyntaxError – an exception indicating that the parser encountered invalid Python code. Related terms: Compile, parsing, error message. Explanation: Syntax errors prevent a script from being compiled into bytecode. Example: Eval("if True print('hi')") raises SyntaxError. Practical application: Detecting coding mistakes early in development. Challenge: Interpreting cryptic line numbers in large, generated code bases.

IndentationError #

IndentationError – a subclass of SyntaxError raised when indentation is inconsistent. Related terms: Whitespace, block, PEP 8. Explanation: Python relies on indentation to define code blocks; mismatched spaces and tabs trigger this error. Example: If True:\Nprint("Hi") – missing indentation raises IndentationError. Practical application: Enforcing readable code structure. Challenge: Configuring editors to insert consistent spaces or tabs.

NameError #

NameError – an exception raised when a local or global name is not found. Related terms: Variable scope, undefined, traceback. Explanation: Occurs when a variable is referenced before assignment or when a typo is made. Example: Print(undef_var) raises NameError. Practical application: Debugging misspelled identifiers. Challenge: Tracking down dynamic name creation in large codebases.

AttributeError #

AttributeError – an exception thrown when an object does not have a requested attribute. Related terms: Getattr, dir, introspection. Explanation: Often results from calling a method that does not exist for that object type. Example: "Text".Append("more") raises AttributeError. Practical application: Providing clear error messages for API misuse.

June 2026 intake · open enrolment
from £99 GBP
Enrol