Sub topic 2
Python Decorators: The `@` Syntax and Reassignment
Assume you know how to define functions, pass positional and keyword arguments, and import standard-library modules. A decorator is a callable that receives a function and returns a replacement function.
The `@` syntax is shorthand for reassignment
These two forms are equivalent:
def shout(func):
def wrapper():
return func().upper()
return wrapper
def greet():
return "hello"
greet = shout(greet)
print(greet()) # HELLO@shout
def greet():
return "hello"
print(greet()) # HELLOPython evaluates shout(greet) after creating greet, then assigns the returned wrapper back to the name greet.
Keeping name and docstring with `functools.wraps`
A wrapper replaces the original function, so its metadata, such as __name__ and __doc__, can be lost. functools.wraps copies important metadata to the wrapper.
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
"""Return the sum of two numbers."""
return a + b
print(add(2, 3))
print(add.__name__) # add
print(add.__doc__) # Return the sum of two numbers.The *args and **kwargs parameters let the wrapper forward any positional or keyword arguments.
Stacking decorators and application order
Decorators stack from the bottom upward. In this example, italic runs first during decoration, and bold wraps its result.
import functools
def bold(func):
@functools.wraps(func)
def wrapper():
return "<b>" + func() + "</b>"
return wrapper
def italic(func):
@functools.wraps(func)
def wrapper():
return "<i>" + func() + "</i>"
return wrapper
@bold
@italic
def greet():
return "hi"
print(greet()) # <b><i>hi</i></b>Decorators that take arguments
A decorator factory is a function that accepts configuration and returns a decorator. It adds one nesting level.
import functools
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def say(message):
print(message)
say("hello")@repeat(times=3) means say = repeat(times=3)(say). Forgetting the call, as in @repeat, passes the function where times is expected.
Exercise
Rewrite @bold followed by @italic as an explicit assignment.
Show answer
greet = bold(italic(greet)).