Python Decorators: Matryoshka Dolls of Code
Python Decorators: Matryoshka Dolls of Code
Every Python learner meets decorators. A magic @ symbol that enhances functions like Popeye eating spinach. But heres the secret: decorators are just wrapping paper.
Real Life: Ordering Bubble Tea
You order: pearl milk tea, less sugar, no ice, add coconut jelly.
- Base function = plain milk tea (nothing)
- Less sugar = decorator 1: modifies behavior
- No ice = decorator 2: changes more
- Add jelly = decorator 3: adds new feature
Each decorator keeps the tea essence but adds flavor. Decorators to functions = toppings to tea.
Simplest Decorator: 3 Lines
def my_decorator(func):
def wrapper():
print("before")
func()
print("after")
return wrapper
@my_decorator
def say_hello():
print("hello")
say_hello()@my_decorator = say_hello = my_decorator(say_hello). Your original function becomes argument, gets wrapped, replaced. That is matryoshka dolls.
With Parameters
def timer(func):
import time
def wrapper(*args,**kwargs):
start=time.time()
result=func(*args,**kwargs)
print(f"took {time.time()-start:.3f}s")
return result
return wrapperAdd timing to ANY function without changing its code. No code modification, just enhancement.
Summary
Decorator = Python express delivery. You dont open the box (original function) to add labels, protection, tracking. Three words: wrap, replace, enhance.