PCAP study materials
PCAP study resources

PCAP key terms

PCAP · Get comfortable with the vocabulary.

__init__.py

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.

Related: Regular package, __all__, Namespace package
Namespace package

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.

Related: __init__.py, Regular package, sys.path
Regular package

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.

Related: __init__.py, Namespace package, Relative import
sys.path

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.

Related: Module search order, Namespace package, Absolute import
Module search order

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.

Related: sys.path, sys.modules, Absolute import
sys.modules

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.

Related: Module search order, Module-level code, Import side effects
Absolute import

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.

Related: Relative import, sys.path, Regular package
Relative import

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.

Related: Absolute import, Regular package, __init__.py
__all__

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.

Related: __init__.py, Star import, Name mangling
Star 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.

Related: __all__, sys.modules, Absolute import
__name__

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.

Related: Module-level code, Import side effects, sys.modules
Module-level code

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.

Related: sys.modules, __name__, Import side effects
Import side effects

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.

Related: Module-level code, __name__, sys.modules
ImportError

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.

Related: ModuleNotFoundError, Exception hierarchy, try/except/else
ModuleNotFoundError

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.

Related: ImportError, Exception hierarchy, AttributeError
Exception hierarchy

The inheritance tree rooted at BaseException, where most ordinary errors derive from Exception; catching a parent class also catches all of its subclasses.

Related: BaseException, except clause order, Custom exception
BaseException

The root of all built-in exceptions, including SystemExit, KeyboardInterrupt, and GeneratorExit; catching it broadly is discouraged because it intercepts those control-flow signals.

Related: Exception hierarchy, except clause order, raise from
except clause order

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.

Related: Exception hierarchy, try/except/else, BaseException
try/except/else

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.

Related: finally block, except clause order, Exception chaining
finally block

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.

Related: try/except/else, Context manager, Exception chaining
raise from

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.

Related: Exception chaining, BaseException, Custom exception
Exception chaining

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.

Related: raise from, finally block, Exception hierarchy
Custom exception

A user-defined class that inherits from Exception or a subclass of it, letting callers catch application-specific failures distinctly from built-in ones.

Related: Exception hierarchy, raise from, except clause order
assert statement

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.

Related: AssertionError, Exception hierarchy
AssertionError

The exception raised when an assert statement's condition evaluates as false, optionally carrying the message expression given after the comma.

Related: assert statement, Exception hierarchy
String immutability

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.

Related: Slice, String methods returning new strings, Interning
Slice

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.

Related: String immutability, Negative indexing, str.join
Negative indexing

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.

Related: Slice, String immutability
str.join

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.

Related: str.split, String methods returning new strings, String immutability
str.split

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.

Related: str.join, String methods returning new strings
String methods returning new strings

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.

Related: String immutability, str.join, Slice
Interning

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 ==.

Related: String immutability, Identity vs equality
Identity vs equality

The distinction between is, which tests whether two names reference the same object, and ==, which tests value equality by invoking eq on the operands.

Related: __eq__, Interning, __str__ vs __repr__
__str__ vs __repr__

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.

Related: __eq__, Identity vs equality, Special methods
__eq__

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.

Related: Identity vs equality, __str__ vs __repr__, Special methods
Special methods

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.

Related: __eq__, __str__ vs __repr__, Class attribute vs instance attribute
Instance attribute

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.

Related: Class attribute vs instance attribute, Name mangling, super()
Class attribute vs instance attribute

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.

Related: Instance attribute, Name mangling, Method resolution order
Name mangling

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.

Related: Instance attribute, Method resolution order, __init__.py
Method resolution order

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.

Related: super(), Class attribute vs instance attribute, Name mangling
super()

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.

Related: Method resolution order, Instance attribute
List comprehension

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.

Related: Generator expression, Lambda, Closure
Generator expression

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.

Related: List comprehension, Lambda, Closure
Lambda

An expression creating an anonymous function with a single expression body whose value is returned implicitly; it cannot contain statements or assignments.

Related: Closure, List comprehension, Late binding
Closure

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.

Related: nonlocal, Late binding, Lambda
nonlocal

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.

Related: Closure, Late binding
Late binding

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.

Related: Closure, Lambda, nonlocal
Context manager

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.

Related: finally block, File open modes
File open modes

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.

Related: Context manager, Text vs binary mode
Text vs binary mode

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.

Related: File open modes, Context manager