Decorator (Python)
A decorator is a function that wraps another function to add behavior before or after it, without changing the original code. You apply one with the @ symbol above a function.
Python
Decorators are common in frameworks for things like routing, caching, and access control. Under the hood, @my_decorator on a function is shorthand for reassigning the function to my_decorator(function).
Syntax
@decorator
def func():
...Examples
Python
def shout(func):
def wrapper():
return func().upper()
return wrapper
@shout
def greet():
return "hi"
print(greet())Output:
HI