Understanding Decorators
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure.
Decorators are usually called before the definition of a function you want to decorate.
Basic Example
Here is how you define a simple decorator:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_whee():
print("Whee!")
say_whee()
Explanation
- The
@my_decoratorsyntax is just syntactic sugar. - It passes the
say_wheefunction tomy_decorator. - It replaces
say_wheewith the returnedwrapperfunction.
You will see decorators everywhere in frameworks like Flask or FastAPI!