Decorators and Closures Flashcards
7 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 7 Decorators and Closures flashcards as text
What is a 'decorator factory' in Python?
Answer: A function that returns a decorator, allowing decorators to accept arguments
A decorator factory is a function that accepts arguments and returns a decorator, allowing you to create parameterized decorators.
When multiple decorators are stacked, in what order are they applied to the function? @decorator_A @decorator_B def my_func(): pass
Answer: decorator_B first, then decorator_A
Decorators are applied bottom-up, so decorator_B is applied first, then decorator_A wraps the result, equivalent to my_func = decorator_A(decorator_B(my_func)).
What is the purpose of the nonlocal keyword in Python closures?
Answer: To allow an inner function to modify a variable in the enclosing (non-global) scope
nonlocal allows an inner function to modify (not just read) a variable defined in its enclosing but non-global scope.
What is a 'free variable' in the context of Python closures?
Answer: A variable used in a function but defined in an enclosing outer scope
A free variable is a variable referenced inside a function but not defined in that function's local scope — it is bound in an enclosing scope and captured by the closure.
What attribute of a Python function object holds the free variables captured by a closure?
Answer: __closure__
The __closure__ attribute is a tuple of cell objects containing the values of variables captured by the closure, or None if the function captures no free variables.
How many levels of function nesting are typically needed to create a parameterized decorator (a decorator that accepts its own arguments)?
Answer: 3 levels — outer accepts args, middle accepts func, inner wraps the call
A parameterized decorator requires three levels: the outermost function accepts the decorator's arguments, the middle function accepts the target function, and the innermost function wraps the actual call.
Can a decorator be applied to a class definition in Python?
Answer: Yes, class decorators receive the class as their argument and return a modified class
Class decorators work the same way as function decorators — they receive the class as their argument and return a modified or replacement object.