Lesson · Python Internals
Function & Code Objects
80 min readFunction & Code Objects
A Python function object wraps executable code plus defaults, globals, annotations, and closure state. The underlying code object describes compiled instructions and local-variable metadata.
Learning goals
- Explain what
defcreates: a function object wrapping an immutable code object plus defaults and closure references. - Read
co_varnamesandco_freevarsand say what each distinguishes. - Inspect
__defaults__and explain why defaults are evaluated once, at definition time. - Inspect
__closure__cells and explain why a closure captures a binding rather than a frozen value. - Handle a function as data: store it, pass it, and inspect its attributes without calling it.
Mental model
A function is not just code: it is a code object plus the runtime context captured where the def executed. The code object is immutable and shared by every function created from the same def line, while defaults and closure cells are per-function state, which is why two closures built by two outer calls see different values.
Mental model
read it top to bottom
def outer(scale):
offset = 3
def transform(value=10): ...
return transform
↓
transform is a function object
├─ __code__ compiled instructions and metadata (co_varnames, co_freevars)
├─ __defaults__ (10,) captured at definition time
└─ __closure__ cells holding the bindings for scale and offsetCore idea
Defining a function creates a function object that pairs an immutable code object, holding the compiled instructions and metadata, with mutable runtime context: defaults captured once at def time and closure cells that keep enclosing bindings alive. Calls then execute the same code against different context. This split is why inspection is useful: __code__ explains what will run, while __defaults__ and __closure__ explain what it will see when it runs.
Function object
Defining a function creates a function object and binds its name. That object can be stored, passed, inspected, decorated, or called later.
Code object
A code object is an immutable compiled description of executable Python code, including bytecode and metadata. A function object adds globals, defaults, annotations, and closure references.
Defaults
Defaults are the values captured for a function's parameters when the def statement executes, stored as a tuple on the function object's __defaults__ attribute (keyword-only defaults go to __kwdefaults__). They are evaluated once, at definition time, not per call, which is why a list or dict used as a default is shared by every call that omits the argument.
Closures
A closure keeps references to names from an enclosing function scope after that outer call has returned. The captured binding, not a frozen snapshot of its value, is what matters.
__code__
A function's __code__ attribute refers to its code object, which stores compiled instructions and metadata such as local variable names. The function object adds runtime context around that code.
__defaults__
__defaults__ is the function attribute holding a tuple of positional-parameter defaults, filled when the def runs and readable or writable afterward. Its length decides how many trailing positional parameters are optional; editing it changes the defaults for every subsequent call, which makes it a useful inspection tool and a rarely wise production trick.
__closure__
A closure keeps references to names from an enclosing function scope after that outer call has returned. The captured binding, not a frozen snapshot of its value, is what matters.
Walkthrough
outer(2)runs the outer body, creates a newtransformfunction withvalue=10recorded in its defaults and cells forscaleandoffset, then returns it; the names local toouterare gone, but the bindings the inner function needs survive in closure cells.fn.__code__.co_varnameslists the local names belonging totransformitself, here just the argumentvalue, whileco_freevars(not printed) would listoffsetandscale, the names it takes from the enclosing scope.fn.__defaults__is the tuple(10,); it was captured when thedefexecuted, so every call that omitsvalueuses that same object rather than a fresh 10.[cell.cell_contents for cell in fn.__closure__]opens each cell and reads its current binding, so the print shows the captured values forscaleandoffset(2 and 3), ordered byco_freevars.- Predict before running: the three printed lines, and what
fn(1)returns when the default is overridden.
Experiments to try
- Call
outer(2)andouter(5)and print both__closure__contents; confirm each function kept its own bindings instead of sharing a snapshot. - Add a list default such as
def transform(value=10, seen=[]), call it twice, and print__defaults__after each call to show the shared list accumulating. - Read
fn.__code__.co_freevarsandfn.__code__.co_argcount, then match each closure cell to its name. - Pass
fntosortedas a key function and store it in a list, then call it through the list entry; confirm a function object is data you can move around.
Common mistakes
- Calling a function with a mutable default and expecting a fresh object: the default is created once at
deftime and stored in__defaults__, so every call that omits the argument shares and accumulates state. - Believing a closure freezes a value: the cell holds the binding, so closures created in a loop all see the final value of the loop variable.
- Expecting
__code__to carry runtime context: the code object is immutable and shared, while defaults, closure cells, and globals live on the function object around it. - Reading
co_varnamesas every name the function touches: it lists arguments and locals only, while globals and attributes are resolved through other metadata at call time.
Practice: Easy
- Run the worked example and label each print: which reads the code object, which reads the defaults, which reads the closure.
- Add
print(fn.__code__.co_freevars)and match those names againstco_varnames; write which names are local totransformand which come fromouter. - Call
fn()andfn(1)and compute the expected results by hand from__defaults__and__closure__; check the outputs against your arithmetic.
Practice: Medium
- Write
make_counter()that returns a closure incrementing its own count variable; inspect__closure__before and after calls and explain why the cell changes while the code object does not. - Create two closures from the same factory with different captured values and show that
fn1.__code__ is fn2.__code__isTruewhile their__closure__contents differ. - Add a mutable default parameter to a function and call it three times; print
__defaults__each time and explain the accumulation using where defaults are stored.
Practice: Hard
- Inventory a nested function: print
__code__,__defaults__,__closure__,__globals__ is globals(), andco_varnames/co_freevars; annotate each attribute with the context it carries and the context it does not. - Build a late-binding lab: create three closures in a loop that reference the loop variable, show they all print the same value, then fix it with a default argument and explain the fix in terms of where the binding is captured.
- Write a small decorator that records the wrapped function's
__name__, wrap a function with it, and inspect which attributes belong to the wrapper and which to the original.
Lesson checklist
- I can name the three runtime pieces a function object carries:
__code__, defaults, and closure cells. - I can read
co_varnamesandco_freevarsand say which names are local and which are captured. - I can explain why two closures from the same factory share a code object but not a binding.
- I can show why a mutable default is shared across calls and what to use instead.
Remember
A function object is a code object plus context: compiled instructions and metadata in `__code__`, defaults captured at definition time in `__defaults__`, and closure cells in `__closure__` that keep the enclosing bindings alive. The same code object backs every function created from one `def`, while defaults and cells differ per creation, which is exactly why mutable defaults leak state and late-bound loop variables surprise people.
Interview angles
What is the main purpose of **Function object**?+
Defining a function creates a function object and binds its name. That object can be stored, passed, inspected, decorated, or called later.
What should you pay attention to when using **Code object**?+
A code object is an immutable compiled description of executable Python code, including bytecode and metadata. A function object adds globals, defaults, annotations, and closure references.
How does **Defaults** fit into this lesson?+
Defaults are captured when the def statement executes and stored as a tuple on __defaults__, so they are evaluated once rather than per call. That timing is why a mutable default is shared by every call that omits the argument.
What is the shared-state trap with a mutable default argument, and why does it happen?+
The default object is created once when the def statement executes and stored in __defaults__, so every call that omits the argument receives the same object, and a function that mutates it accumulates state across calls. Create the object inside the function, or use a None sentinel, when each call needs a fresh container.