1.Function decorators
A decorator is a function that takes a function and returns a replacement for it. @my_decorator above def process(): is exactly process = my_decorator(process), just written before the definition instead of after.
Key features
- @my_decorator above a def is sugar for name = my_decorator(name), run once at def time
- A decorator takes one function argument and returns a callable to replace it
- The replacement is usually a wrapper() closure that calls the original inside itself
- Decoration happens once, at module load — not on every call to the decorated function
- wrapper(*args, **kwargs) must forward every argument, and return, to work for any function
@decorator syntax and its plain-assignment equivalent
- def process(): ... — the original function object is built
- my_decorator(process) — runs once, at def time, and returns wrapper
- process = wrapper — the name process now points at wrapper instead
Command
def my_decorator(func):
def wrapper(*args, **kwargs):
# do something before
result = func(*args, **kwargs)
# do something after
return result
return wrapper
@my_decorator
def process():
pass@my_decorator above def is exactly name = my_decorator(name) — decoration runs once at def time, and wrapper must forward every argument and the return value.