What is Decorator in Python: Simple Explanation and Example
decorator in Python is a special function that modifies the behavior of another function without changing its code. It wraps the original function to add extra features or actions before or after it runs.How It Works
Think of a decorator like a gift wrapper for a present. The present is the original function, and the wrapper adds some decoration or extra features without changing the gift inside. When you call the wrapped function, the decorator can do something before or after the original function runs.
In Python, a decorator is a function that takes another function as input and returns a new function that usually calls the original one but with added behavior. This lets you reuse common code like logging, timing, or checking permissions without repeating it inside every function.
Example
This example shows a simple decorator that prints a message before and after calling the original function.
def my_decorator(func): def wrapper(): print("Before the function runs") func() print("After the function runs") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()
When to Use
Use decorators when you want to add the same extra behavior to many functions without repeating code. For example, you can use decorators to:
- Log when a function starts and ends
- Check if a user has permission before running a function
- Measure how long a function takes to run
- Cache results to speed up repeated calls
This keeps your code clean and easy to maintain by separating the extra tasks from the main function logic.
Key Points
- A decorator is a function that wraps another function to change its behavior.
- It helps add reusable features like logging or permission checks.
- Use the
@decorator_namesyntax to apply a decorator. - Decorators keep code clean by separating concerns.