Decorators & Closures Mechanics Practice & CPython Execution Tracing
Master closure cell manipulation, decorator stacking, memory retention, functools internals, and advanced function wrapping patterns.
CPython Runtime Semantics: Decorators & Closures Mechanics
In Python, functions are first-class citizen objects capable of being bound to identifiers, passed as parameters, and returned from higher-order functions. A closure captures free variables from its enclosing lexical scope using CPython cell objects (PyCellObject). Decorators utilize this metaprogramming primitive to wrap callables, enabling transparent caching, validation, instrumentation, and access control at definition time.
When an inner function references an outer local variable, CPython allocates a PyCellObject on the heap to store the pointer. Both the outer and inner stack frames access the variable via the LOAD_DEREF and STORE_DEREF opcodes rather than LOAD_FAST. Because the cell object resides on the heap, the inner function retains access to the variable even after the outer function frame returns and terminates.
Closures look up free variables when invoked, not when defined. Creating lambdas inside a loop (such as [lambda: i for i in range(5)]) causes all five functions to reference the same cell object containing the loop's final value (4). Fix this by binding the variable into default argument scope: lambda i=i: i. Furthermore, decorators must use @functools.wraps(fn) to prevent overwriting the wrapped function's __name__ and __doc__.
Worked Decorators & Closures Mechanics Trace Walkthroughs
Before launching the interactive sandbox, study these worked execution traces. Predict the state mutation for every instruction, then inspect the line-by-line execution table to understand why CPython produces each result.
Walkthrough 1: Mutating Closure Variables via __closure__
Difficulty: harddef make_adder(x):
def adder(y):
return x + y
return adder
f = make_adder(10)
cell = f.__closure__[0]
cell.cell_contents += 5
print(f(5))20The closure captures 'x' in a cell. Accessing __closure__[0] gets this cell. Modifying cell_contents to 15 changes the captured 'x'. Calling f(5) returns 15 + 5 = 20.
Walkthrough 2: Decorator Stacking Execution Order
Difficulty: harddef dec_a(func):
print('A applied')
return func
def dec_b(func):
print('B applied')
return func
@dec_a
@dec_b
def my_func():
passB applied A applied
The syntax @dec_a @dec_b is equivalent to my_func = dec_a(dec_b(my_func)). Thus, dec_b is evaluated first, printing 'B applied', followed by dec_a printing 'A applied'.
Walkthrough 3: Accessing the Original Function via __wrapped__
Difficulty: hardimport functools
def my_dec(func):
@functools.wraps(func)
def wrapper(*args):
return func(*args)
return wrapper
@my_dec
def target():
return 42
print(target.__wrapped__())42functools.wraps copies metadata and sets wrapper.__wrapped__ = func. Calling target.__wrapped__() bypasses the decorator and calls the original target function, returning 42.
Static Problem Bank & Code Walkthrough Preview
The following 8 real problems evaluate core Decorators & Closures Mechanics execution behaviors directly from our CPython test suite. Trace each code snippet manually, predict the terminal output, and compare your mental model with the verified output and technical explanation before testing variations in the interactive workspace.
Basic Expression Completion
# Complete expression so result equals the sum of x and y (15)
x = 5
y = 10
result = ___
print(result)x + yx + y evaluates to 15, which is stored in result and printed.
List Comprehension Filter
# Complete list comprehension to keep even numbers
nums = [1, 2, 3, 4, 5, 6]
evens = [___ for num in nums if num % 2 == 0]
print(evens)numThe expression should be 'num' to collect even numbers: [2, 4, 6].
Nonlocal Binding in Deeply Nested Scopes
def outer():
x = 10
def middle():
def inner():
nonlocal x
x = 20
inner()
middle()
print(x)
outer()20inner() declares nonlocal x. It searches up the scope chain, skipping middle() (which doesn't define x), and finds x in outer(). It modifies outer()'s x to 20.
Check if a String is a Palindrome
# Problem: Determine if a string reads the same forwards and backwards
# Ignore case and non-alphanumeric characters
def is_palindrome(s):
"""
Check if a string is a palindrome.
Args:
s: Input string
Returns:
bool: True if palindrome, False otherwise
"""
# Your implementation heredef is_palindrome(s):
cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]Clean the string by keeping only alphanumeric chars in lowercase, then compare with its reverse.
Two Sum Problem (Hash Map & Array Logic)
# Problem: Find two numbers in an array that add up to a target value
# Return their indices. Assume exactly one solution exists.
def two_sum(nums, target):
"""
Find two indices where corresponding values sum to target.
Args:
nums: List of integers
target: Target sum value
Returns:
list: Two indices [i, j] where nums[i] + nums[j] == target
Constraint: Solve in O(n) time complexity
"""
# Your implementation heredef two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []Single pass through array. For each element, check if its complement was seen before.
Class Decorator Modifying __init__
def add_init_log(cls):
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
print('Init called')
orig_init(self, *args, **kwargs)
cls.__init__ = new_init
return cls
@add_init_log
class MyClass:
def __init__(self):
pass
MyClass()Init calledThe decorator saves the original __init__, replaces it with new_init, and returns the modified class. Instantiating MyClass calls new_init, printing 'Init called' before executing the original __init__.
Closure cell content inspection
def outer(x):
def inner():
return x
return inner
func = outer(10)
print(func.__closure__[0].cell_contents)10The outer function creates a closure capturing x. When we inspect the first cell object in __closure__, its cell_contents shows the value 10 that was passed during the outer(10) call. This demonstrates how closures store their captured variables in cell objects.
Stacked decorator execution order
def decorator1(func):
def wrapper():
print("Decorator1 before")
func()
print("Decorator1 after")
return wrapper
def decorator2(func):
def wrapper():
print("Decorator2 before")
func()
print("Decorator2 after")
return wrapper
@decorator1
@decorator2
def my_func():
print("Original function")
my_func()Decorator1 before Decorator2 before Original function Decorator2 after Decorator1 after
Decorators are applied in reverse order of their stacking. decorator2 is applied first, then decorator1 wraps that result. When called, decorator1's wrapper runs first, then decorator2's wrapper, then the original function, then unwinding back through the decorators in reverse order.
How to use this tool
Study the verified Decorators & Closures Mechanics worked examples above, predict the variable mutations and output on paper, then run variations in the interactive workspace below.
Worked example
# Quick verification check for Decorators & Closures Mechanics x = 10 y = x print(x, y)
Static result: 10 10
Controls
Review the test snippet in the editor, click Run to execute in the local Pyodide sandbox, and inspect the stdout console and state changes below.
Honest limits
Exercises for Decorators & Closures Mechanics run client-side via WebAssembly (Pyodide). Standard library features are supported; GUI and external network calls are disabled for sandboxing.
Continue with the Python Mastery Hub.
Interactive Dry-Run Execution Workspace
Closure Retaining Large Object Memory
Trace CPython execution step-by-step and deduce the exact stdout string emitted by this snippet.
import sys
def create_closure():
large_data = [0] * 1000000
def inner():
return len(large_data)
return inner
f = create_closure()
print(sys.getsizeof(f.__closure__[0].cell_contents) > 1000)Closures and Late Binding in Python Scopes
Trace how nested functions bind free variables from enclosing frames, how cell objects work under the hood, and how to avoid the late-binding loop variable trap.
Frequently Asked Questions: Decorators & Closures Mechanics
Why do functions created in loops all return the same value when called later?
Python closures bind to variables, not values (late binding). All created functions point to the identical cell object holding the loop variable. When invoked later, they look up the variable's current value, which is whatever the final loop iteration assigned.
How does @functools.wraps preserve function introspection in production code?
Decorating a function replaces it with an inner wrapper function, obscuring the original name, docstring, and annotations. @functools.wraps copies attributes (__name__, __doc__, __module__, __annotations__) from the wrapped callable onto the wrapper.
What is the execution order when multiple decorators are applied to one function?
Decorators are applied from the bottom up (inside out) at function definition time, but execute from the top down (outside in) when the decorated function is invoked.