PCAP key terms
PCAP · Get comfortable with the vocabulary.
- __init__.py
- Related: Regular package, __all__, Namespace package
A file whose presence marks a directory as a regular package, executed when the package is imported; it can initialize package state, define all, or be empty in modern Python.
- Namespace package
- Related: __init__.py, Regular package, sys.path
A package created from a directory without init.py, allowing portions of a package to be spread across multiple locations on the search path and merged at import time.
- Regular package
- Related: __init__.py, Namespace package, Relative import
A directory containing an init.py file, imported as a single unit whose submodules are found relative to the package directory rather than the top-level search path.
- sys.path
- Related: Module search order, Namespace package, Absolute import
The list of directory strings that the import system searches, in order, when resolving a top-level module name; the first match wins and the current script directory usually comes first.
- Module search order
- Related: sys.path, sys.modules, Absolute import
The sequence the importer follows to locate a module: built-in modules, then frozen modules, then directories listed in sys.path, with earlier hits shadowing later ones.
- sys.modules
- Related: Module search order, Module-level code, Import side effects
A dictionary caching every module already imported, keyed by module name; a second import of the same name returns the cached object instead of re-executing the module body.
- Absolute import
- Related: Relative import, sys.path, Regular package
An import statement naming a module by its full path from the project root or top-level package, unaffected by the location of the importing file.
- Relative import
- Related: Absolute import, Regular package, __init__.py
An import using leading dots to refer to sibling or parent modules within the same package, where one dot means the current package and each extra dot climbs one level.
- __all__
- Related: __init__.py, Star import, Name mangling
A module-level list of names that defines what a star import pulls in and is also consulted by documentation tools; without it, star import takes all names not starting with underscore.
- Star import
- Related: __all__, sys.modules, Absolute import
The statement from module import *, which binds the module's public names into the current namespace; discouraged inside functions because it obscures where names originate.
- __name__
- Related: Module-level code, Import side effects, sys.modules
A module-level string holding the module's name as imported, or the literal 'main' when the file is run as a script, enabling the if name == 'main' guard.
- Module-level code
- Related: sys.modules, __name__, Import side effects
Statements outside any function or class that execute once, top to bottom, the first time a module is imported, and are skipped on later imports because of caching.
- Import side effects
- Related: Module-level code, __name__, sys.modules
Observable actions such as printing, file access, or network calls performed while a module body executes at import time, which is why guarding executable code is recommended.
- ImportError
- Related: ModuleNotFoundError, Exception hierarchy, try/except/else
The exception raised when an import statement cannot locate the requested module or a name inside it; ModuleNotFoundError is a subclass used when the module itself is missing.
- ModuleNotFoundError
- Related: ImportError, Exception hierarchy, AttributeError
A subclass of ImportError raised specifically when the named module cannot be found at all, distinguishing a missing module from a missing attribute within an existing one.
- Exception hierarchy
- Related: BaseException, except clause order, Custom exception
The inheritance tree rooted at BaseException, where most ordinary errors derive from Exception; catching a parent class also catches all of its subclasses.
- BaseException
- Related: Exception hierarchy, except clause order, raise from
The root of all built-in exceptions, including SystemExit, KeyboardInterrupt, and GeneratorExit; catching it broadly is discouraged because it intercepts those control-flow signals.
- except clause order
- Related: Exception hierarchy, try/except/else, BaseException
The rule that handlers are tested top to bottom and only the first matching one runs, so more specific exception classes must be listed before their parent classes.
- try/except/else
- Related: finally block, except clause order, Exception chaining
A compound statement where except blocks run only on failure and the else block runs only when no exception occurred, keeping success-only code out of the guarded region.
- finally block
- Related: try/except/else, Context manager, Exception chaining
A block that always executes after try and any handlers, whether the try succeeded, raised, or exited via return, break, or continue, making it suitable for cleanup.
- raise from
- Related: Exception chaining, BaseException, Custom exception
Syntax that raises a new exception while recording an explicit cause, setting cause and producing a chained traceback that shows both the original and the new error.
- Exception chaining
- Related: raise from, finally block, Exception hierarchy
The automatic linking of a new exception to the one being handled, stored in context, so the traceback displays the original failure alongside the replacement.
- Custom exception
- Related: Exception hierarchy, raise from, except clause order
A user-defined class that inherits from Exception or a subclass of it, letting callers catch application-specific failures distinctly from built-in ones.
- assert statement
- Related: AssertionError, Exception hierarchy
A debugging check that raises AssertionError when its condition is false; assertions are removed when the interpreter runs with optimization enabled, so they must not enforce runtime rules.
- AssertionError
- Related: assert statement, Exception hierarchy
The exception raised when an assert statement's condition evaluates as false, optionally carrying the message expression given after the comma.
- String immutability
- Related: Slice, String methods returning new strings, Interning
The property that string objects cannot be changed after creation, so every operation that appears to modify one actually builds and returns a new string object.
- Slice
- Related: String immutability, Negative indexing, str.join
The expression seq[start:stop:step] that returns a new sequence of selected items; omitted bounds default sensibly and negative indices count from the end.
- Negative indexing
- Related: Slice, String immutability
Accessing elements by counting backward from the end of a sequence, where -1 is the last item and -len is the first, valid for both indexing and slicing.
- str.join
- Related: str.split, String methods returning new strings, String immutability
A method called on a separator string that concatenates an iterable of strings, inserting the separator between elements; it raises TypeError if any element is not a string.
- str.split
- Related: str.join, String methods returning new strings
A method that divides a string into a list of substrings, splitting on whitespace runs when no separator is given or on the exact separator otherwise.
- String methods returning new strings
- Related: String immutability, str.join, Slice
Methods such as upper, strip, replace, and title that never alter the original object but return a freshly allocated string, so the result must be reassigned to persist.
- Interning
- Related: String immutability, Identity vs equality
An implementation optimization that reuses one object for certain strings, such as short literals, so identity comparison may succeed for equal values; equality should still be tested with ==.
- Identity vs equality
- Related: __eq__, Interning, __str__ vs __repr__
The distinction between is, which tests whether two names reference the same object, and ==, which tests value equality by invoking eq on the operands.
- __str__ vs __repr__
- Related: __eq__, Identity vs equality, Special methods
Two special methods for textual representation: repr aims at unambiguous developer output used in containers and the REPL, while str aims at readable output for end users via print.
- __eq__
- Related: Identity vs equality, __str__ vs __repr__, Special methods
The special method invoked by the == operator to compare values; defining it usually requires also defining hash if instances are to remain usable in sets and dict keys.
- Special methods
- Related: __eq__, __str__ vs __repr__, Class attribute vs instance attribute
Methods with double-underscore names, such as len, iter, and add, that the interpreter calls implicitly to support operators and built-in functions on instances.
- Instance attribute
- Related: Class attribute vs instance attribute, Name mangling, super()
A value stored per object, typically assigned in init through self, that shadows a class attribute of the same name and is looked up first on the instance.
- Class attribute vs instance attribute
- Related: Instance attribute, Name mangling, Method resolution order
A class attribute is defined on the class and shared by all instances until shadowed; an instance attribute belongs to one object and takes precedence in attribute lookup.
- Name mangling
- Related: Instance attribute, Method resolution order, __init__.py
The compiler's rewriting of identifiers with two leading underscores and at most one trailing underscore into _ClassName__name, which reduces accidental overriding in subclasses.
- Method resolution order
- Related: super(), Class attribute vs instance attribute, Name mangling
The linearized sequence in which base classes are searched for an attribute, computed by the C3 algorithm and exposed as the mro attribute of a class.
- super()
- Related: Method resolution order, Instance attribute
A built-in returning a proxy that delegates attribute lookup to the next class in the method resolution order, commonly used to call a parent's init cooperatively.
- List comprehension
- Related: Generator expression, Lambda, Closure
A compact expression such as [f(x) for x in data if cond] that builds a new list in one statement, with optional filtering and multiple for clauses evaluated left to right.
- Generator expression
- Related: List comprehension, Lambda, Closure
A lazily evaluated construct written with parentheses that yields items one at a time as consumed, using less memory than a list comprehension for large inputs.
- Lambda
- Related: Closure, List comprehension, Late binding
An expression creating an anonymous function with a single expression body whose value is returned implicitly; it cannot contain statements or assignments.
- Closure
- Related: nonlocal, Late binding, Lambda
A nested function that retains access to variables from its enclosing scope after that scope has finished executing, reading them through cells rather than copies.
- nonlocal
- Related: Closure, Late binding
A declaration letting an inner function rebind a name that lives in an enclosing function's scope, instead of creating a new local variable of the same name.
- Late binding
- Related: Closure, Lambda, nonlocal
The behavior whereby a closure or lambda looks up free variables when it is called, not when it is defined, so loops can capture the final value of a variable.
- Context manager
- Related: finally block, File open modes
An object implementing enter and exit that can be used in a with statement, guaranteeing setup and teardown such as closing a file even when errors occur.
- File open modes
- Related: Context manager, Text vs binary mode
Single-character flags passed to open, such as r for read, w for truncate-and-write, a for append, and b or + modifiers for binary and read-write access.
- Text vs binary mode
- Related: File open modes, Context manager
Text mode reads and writes str with an encoding and newline translation, while binary mode reads and writes bytes without translation and requires encoded data.