Decorators in Python are a powerful and elegant way to modify or enhance the behavior of functions or methods without changing their actual code.
What is a decorator?
A decorator is essentially a function that takes another function as input and
returns a new function that adds some kind of functionality before or after the original function runs.
You apply decorators using the @decorator_name syntax placed just above the function definition.
Why use decorators?
To add reusable functionality (e.g., logging, timing, access control) to many functions without repeating code.
To keep your code clean and separate concerns.
Basic example of a decorator
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()
Output:
Before the function runs
Hello!
After the function runs
How it works:
@my_decorator is syntactic sugar for:
say_hello = my_decorator(say_hello)
When you call say_hello(), it actually calls wrapper(), which runs extra code around the original function.
Decorators with arguments
To decorate functions that take parameters, your wrapper function should accept
*args and **kwargs:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Decorators in Python are a powerful and elegant way to modify or enhance the behavior of functions or methods without changing their actual code.
What is a decorator?
@decorator_namesyntax placed just above the function definition.Why use decorators?
Basic example of a decorator
Output:
How it works:
@my_decoratoris syntactic sugar for:When you call
say_hello(), it actually callswrapper(), which runs extra code around the original function.Decorators with arguments
To decorate functions that take parameters, your wrapper function should accept
*argsand**kwargs:Summary
@staticmethod,@classmethod, and@property.