01Simple decorator
main.py
def shout(func):
def wrapper():
return func().upper()
return wrapper
@shout
def greet():
return "hello"
print(greet())Output
HELLO
Python decorators explained: wrap functions, add behavior, build decorators with arguments, and preserve metadata with functools.wraps.
def shout(func):
def wrapper():
return func().upper()
return wrapper
@shout
def greet():
return "hello"
print(greet())HELLO
def repeat(n):
def decorator(func):
def wrapper():
for _ in range(n):
func()
return wrapper
return decorator
@repeat(3)
def hi():
print("hi")
hi()hi hi hi
from functools import wraps
def logged(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Calling", func.__name__)
return func(*args, **kwargs)
return wrapper
@logged
def add(a, b):
return a + b
print(add(2, 3))Calling add 5