Conceptual
Login

Writing Python Functions with Lambda, Decorators, and Bytecode

This content covers Python's function model: a function is fundamentally an object composed of a `CodeType` (compiled bytecode and metadata) wrapped by a `FunctionType` (the callable interface), and any callable in Python is defined by implementing the `__call__` dunder method on a class instance. Building on this, alternative function-creation mechanisms are introduced, including anonymous single-expression functions (`lambda`), partial application (fixing a subset of a function's arguments to derive a new function), decorators (higher-order functions that wrap and modify a function's parameters or return value at runtime), dynamic code execution (`exec`/`eval` invoking the interpreter on generated source), and runtime class construction (`types.new_class`). The unifying theoretical point is that Python's object model treats functions and classes as first-class, mutable, dynamically constructible objects, which is why state can be attached to a function object and why callables can be synthesized programmatically rather than only via `def`.