@deco written above def f(): … is equivalent to which statement?
The name f is rebound to whatever the decorator returns.
Decorators · Exercise 1 of 4
Fifteen multiple-choice questions on Python decorators: the @ syntax, wrappers, functools.wraps, when decorators run, arguments, stacking, closures and built-in decorators. Pick an option to check your answer instantly.
@deco written above def f(): … is equivalent to which statement?
The name f is rebound to whatever the decorator returns.
Which description fits a decorator?
It adds behaviour without changing the original function's code.
Why should a wrapper be written as def wrapper(*args, **kwargs)?
The same decorator can then wrap f(), f(a) and f(a, b=1).
What problem does @functools.wraps(func) solve?
It copies metadata from func to the wrapper and sets __wrapped__.
When does the code in a decorator's body (outside the wrapper) run?
The wrapper's body is what runs on every call.
How many nested function levels does a decorator used as @retry(times=3) typically need?
retry(times=3) is called first and must return the actual decorator.
What is @a / @b / def f(): … equivalent to?
The decorator nearest the def is applied first; at call time a's wrapper runs first.
A decorator defines a wrapper but has no return wrapper. What happens when the decorated function is called?
The decorator returned None, so the function name is bound to None.
How does the wrapper still know which function to call after the decorator has returned?
The enclosing scope's variables live on as long as the inner function needs them.
In a class used as a decorator, which method runs when the decorated function is called?
__init__ runs once with the function; the decorated name refers to the instance, and calling an instance runs __call__.
Timed online tests with instant scores and explanations.