Writing a decorator in Python
Wrapping a function to add behavior around it.
import functools
def shout(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
return result.upper() + "!"
return wrapper
@shout
def greet(name):
return f"hello {name}"
loud = greet("world")
How it works
shoutreturns awrapperthat calls the original.@functools.wrapskeeps the wrapped name and docstring.@shoutabovegreetrebinds it to the wrapper.
Keywords and builtins used here
defgreetreturnshoutwrapper
The run, in numbers
- Lines
- 17
- Characters to type
- 229
- Tokens
- 71
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 43 seconds.
Step 2 of 5 in Decorators & closures, step 6 of 53 in Pythonic Python.