How to create and use Python decorators
Answered
14
I see @decorator syntax in Python. How do I create my own decorator?
N
Asked by
noor_code
Gold
•
255 rep
1 Answer
25
import functools
import time
# Basic decorator
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Before function")
result = func(*args, **kwargs)
print("After function")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}")
# Decorator with arguments
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet():
print("Hi!")
H
Bronze
•
565 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer