How to Create a Decorator in Python: Simple Guide
In Python, you create a decorator by defining a function that takes another function as input and returns a new function that adds extra behavior. Use the
@decorator_name syntax above a function to apply the decorator easily.Syntax
A decorator is a function that wraps another function to extend its behavior without changing its code. The basic syntax uses a function that takes a function as input and returns a new function.
- def decorator(func): defines the decorator function.
- def wrapper(): defines the inner function that adds behavior.
- return wrapper returns the new function.
- @decorator applies the decorator to a function.
python
def decorator(func): def wrapper(): # Code before calling the original function func() # Code after calling the original function return wrapper @decorator def my_function(): print("Hello")
Example
This example shows a decorator that prints messages before and after the original function runs. It demonstrates how decorators add behavior without changing the original function's code.
python
def simple_decorator(func): def wrapper(): print("Before the function runs") func() print("After the function runs") return wrapper @simple_decorator def greet(): print("Hello, friend!") greet()
Output
Before the function runs
Hello, friend!
After the function runs
Common Pitfalls
Common mistakes when creating decorators include forgetting to return the wrapper function, not calling the original function inside the wrapper, and losing the original function's name and documentation.
To keep the original function's name and docstring, use functools.wraps from the standard library.
python
import functools def wrong_decorator(func): def wrapper(): print("Before") # Missing func() call here print("After") return wrapper @wrong_decorator def say_hi(): print("Hi!") say_hi() # Correct way with functools.wraps def correct_decorator(func): @functools.wraps(func) def wrapper(): print("Before") func() print("After") return wrapper @correct_decorator def say_hello(): "Prints hello" print("Hello!") say_hello()
Output
Before
After
Hi!
Before
Hello!
After
Quick Reference
Remember these key points when creating decorators:
- Decorators wrap functions to add behavior.
- Use
@decorator_nameto apply decorators. - Always return the wrapper function.
- Call the original function inside the wrapper.
- Use
functools.wrapsto preserve metadata.
Key Takeaways
A decorator is a function that takes another function and returns a new function with added behavior.
Use the @decorator syntax to apply a decorator to a function easily.
Always return the wrapper function and call the original function inside it.
Use functools.wraps to keep the original function's name and documentation.
Decorators help keep code clean by separating extra behavior from core logic.