Writing Custom Decorators
Create decorators using wrapper functions and functools.wraps.
Introduction
Decorators are functions that wrap other functions, adding behavior before or after without modifying the original.
What is a Decorator?
@decorator above a function is syntactic sugar for: func = decorator(func). The decorator receives the function and returns a wrapper.
def shout(func):
def wrapper(*a, **kw):
result = func(*a, **kw)
return str(result).upper()
return wrapper
@shout
def greet(name): return f'hello {name}'
print(greet('Alice'))All lessons in this course
- Functions as First-Class Objects
- Writing Custom Decorators
- The @property Decorator
- @classmethod and @staticmethod