What are decorators in Python and how do I use them?
Decorators are functions that modify the behavior of other functions or methods. Use them to add functionality like logging or access control without changing the original code.
Decorators in Python are a powerful and expressive way to modify or extend the behavior of functions or methods. They are often used for tasks such as logging, access control, or instrumentation. A decorator is essentially a function that takes another function as an argument and returns a new function that usually enhances or alters the behavior of the original function.
To create a decorator, define a function that wraps another function:
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
You can then apply this decorator to a function using the @
symbol:
@my_decorator
def say_hello():
print('Hello!')
When you call say_hello()
, the output will include messages before and after the original function's execution. Decorators can also take arguments and be chained together, providing a flexible mechanism for adding functionality. By leveraging decorators, you can write cleaner and more maintainable code, separating cross-cutting concerns from core logic.