14
I see @decorator syntax in Python. How do I create my own decorator?
Loading...
Q&A · Answered
I see @decorator syntax in Python. How do I create my own decorator?
Accepted answer
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!")Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.