PCAP cheat sheet
PCAP · Keep the key ideas within reach.
Modules and Packages
import x binds the module object in the current namespace; from x import y binds only y, so x itself is not defined afterwards.
import package.submodule binds only the top-level package name; the submodule is reachable as package.submodule after the import executes.
A directory becomes a package when it contains init.py; the file runs on first import and its namespace becomes the package's attributes.
name equals "main" only when the file is run as a script; the if name == "main": guard prevents side effects on import.
sys.path is a list searched in order; sys.path[0] is the script's directory (or '' for interactive/REPL sessions).
Relative imports use leading dots: from . import m (sibling), from ..pkg import m (parent package); they fail in a script run directly.
A module is imported once and cached in sys.modules; a second import returns the cached object without re-executing the file.
from module import * imports only names listed in all if defined; otherwise it imports names not starting with underscore.
Exceptions
except clauses are tested top-down; place the most specific exception classes first because the first matching clause wins.
A bare except: catches everything including SystemExit and KeyboardInterrupt; except Exception: excludes those BaseException-only subclasses.
else runs only when the try block completes without raising; finally always runs, even after return, break, or an uncaught exception.
raise re-raises the active exception inside an except block; raise X from Y sets cause and chains the traceback.
Custom exceptions should subclass Exception; the class name, not its message, determines which except clause matches.
try/except/finally order is fixed: except before else before finally; else cannot appear without at least one except.
An exception raised inside finally replaces any in-flight exception or return value from the try block.
Multiple exceptions are caught with a tuple: except (ValueError, TypeError) as e: - the parentheses are required.
Strings
Strings are immutable sequences of Unicode code points; every 'modifying' method returns a new string.
s.split() with no argument splits on runs of whitespace and drops empty strings; s.split(',') keeps empty fields.
s.join(iterable) inserts s between elements and requires all elements to be str, else TypeError.
Slicing s[i:j:k] returns a new string; negative indices count from the end and out-of-range bounds are clamped, not errors.
f-strings evaluate expressions inside {}; format spec follows a colon, e.g. f"{x:.2f}" or f"{name!r}".
str methods strip/lstrip/rstrip remove characters (default whitespace) only from the ends, never the middle.
find returns -1 when absent; index raises ValueError; both accept optional start and end bounds.
Comparison is lexicographic by code point and case-sensitive; 'a' < 'A' is False because uppercase letters have lower code points.
Object-Oriented Programming
Instance methods receive self; class methods receive cls via @classmethod; static methods receive neither via @staticmethod.
init initializes an already-created instance; new creates it and is rarely overridden except for immutable subclasses.
Name mangling turns __attr (two leading underscores, at most one trailing) into _ClassName__attr inside the class body.
Attribute lookup order: instance dict, then class and its MRO; a data descriptor on the class takes precedence over the instance dict.
super() resolves the next class in the MRO, not necessarily the parent; MRO is computed by the C3 linearization algorithm.
str is for readable output used by print and str(); repr is for unambiguous output used by repr() and the REPL.
Properties created with @property plus @name.setter let attribute access run methods while keeping attribute syntax.
The MRO of class C(A, B) places C first, then A and its ancestors consistent with B; use C.mro() or C.mro to inspect.
Miscellaneous (Comprehensions, Lambdas, Closures, I/O)
A list comprehension [expr for x in it if cond] evaluates expr once per surviving item; a generator expression uses parentheses and is lazy.
Dict and set comprehensions use {k: v for ...} and {x for ...}; a comprehension variable does not leak into the enclosing scope in Python 3.
lambda args: expr creates a function of one expression with no statements; it returns the expression's value implicitly.
A closure captures variables by reference, not value; late binding means all lambdas in a loop see the final loop value unless bound via a default arg.
nonlocal declares assignment to an enclosing function's variable; global does the same for module scope; without either, assignment creates a local.
open(path, mode) modes: 'r' read, 'w' truncate/write, 'a' append, 'x' exclusive create, 'b' binary, '+' read and write; default is 'r' text.
The with statement calls enter and guarantees exit, which closes the file even if an exception occurs inside the block.
sorted(iterable, key=..., reverse=...) returns a new list; key receives each element, so key=len or key=lambda x: x[1] are common.