What is a decorator in Python?
A decorator is a function that takes another function, adds some extra behaviour to it, and returns the new function. You apply it by writing @decorator_name above the function, and the original code stays unchanged.
def shout(func):
def wrapper():
result = func()
return result.upper()
return wrapper
@shout
def greet():
return "hello"
print(greet())
Output:
Tutorials Class - Output Window
HELLO
Writing @shout above greet is the same as writing greet = shout(greet). Decorators are used for logging, timing, login checks and caching. Use functools.wraps inside real decorators to keep the original function name. Learn more in Python Decorators.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |