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 in Python?
Answer: A function that modifies or extends the behavior of another function
A decorator is a function that takes another function as input and returns a modified or extended version of it.
Which symbol is used in Python's decorator syntax?
Answer: @
The @ symbol placed before a function definition applies the decorator to that function.
What does functools.wraps do when used inside a decorator?
Answer: Copies the original function's metadata (like __name__ and __doc__) to the wrapper
functools.wraps preserves the original function's metadata such as its name and docstring, which would otherwise be replaced by the wrapper function's metadata.
What is a closure in Python?
Answer: A function that captures and remembers variables from its enclosing scope
A closure is an inner function that remembers the values from its enclosing scope even when execution has moved outside that scope.
What will the following code print? def outer(): x = 10 def inner(): return x return inner f = outer() print(f())
Answer: 10
The inner function forms a closure over variable x from the outer function's scope, so it can access and return x even after outer has finished executing.
What does the @property decorator do in Python?
Answer: Allows a method to be accessed like an attribute
The @property decorator allows you to define methods that can be accessed like attributes, enabling getter behavior without explicit method calls.
Which of the following is NOT a built-in Python decorator?
Answer: @private
@private is not a built-in Python decorator; Python does not have built-in access modifier decorators, though @staticmethod, @classmethod, and @property are all built-in.