Closures and decorators
Wrap a function and keep access to the original.
An inner function can use names from its enclosing function even after the outer call returns. This is a closure. The wrapper below remembers the original function through the variable function.
Writing @announce above a definition replaces the function with announce(function). A wrapper usually accepts *args and **kwargs to forward positional and keyword arguments. Use functools.wraps to preserve the original name and documentation.
The decorator receives the original greet and returns a wrapper.
Try it yourself
Keep the decorator. Replace greet with a decorated add(a, b) and print its result for 4 and 6.
Target output
Calling add
10Show a hint
Place @announce above def add(a, b): and return a + b.
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
from functools import wraps
def announce(function):
@wraps(function)
def wrapper(*args, **kwargs):
print("Calling", function.__name__)
return function(*args, **kwargs)
return wrapper
@announce
def add(a, b):
return a + b
print(add(4, 6))