Step 1: functions inside functions#
You already know functions are objects that can be passed around. A function can also be defined inside another function and returned:
The inner function multiply remembers the value of n even after make_multiplier has finished. This is called a closure.
Step 2: what is a decorator?#
A decorator is a function that:
- takes a function as input,
- defines a wrapper function that adds some behaviour before/after calling the original,
- returns the wrapper.
Step 3: the @ syntax#
Writing @decorator above a function does exactly the same as func = decorator(func):
Decorator को gift wrapping की तरह समझें। आपका function अंदर का gift है - वह बदलता नहीं। Decorator उसके चारों ओर एक wrapper (रैपर) लगा देता है, जो gift खोलने से पहले और बाद में कुछ extra काम कर सकता है - जैसे log लिखना, समय नापना, या जाँचना कि user logged in है या नहीं।
@announce लिखना बिल्कुल वैसा ही है जैसे say_hello = announce(say_hello) - यानी "say_hello को announce वाले wrapper में लपेट दो।"
Decorating functions with arguments#
Use *args, **kwargs so the wrapper works with any function, and remember to return the result:
Preserving the function's identity: functools.wraps#
Without care, the decorated function "forgets" its name and docstring:
Always use @wraps(func) in your decorators - debugging tools, documentation and frameworks rely on the original name.
Practical decorators#
Timing a function#
Access control (like a login check in web apps)#
This is exactly how Flask's @login_required and Django's @permission_required work.
Caching results (memoisation)#
Python has a built-in caching decorator:
Decorators with their own arguments#
To pass arguments to the decorator itself (like @repeat(3)), add one more level:
Decorators you'll see everywhere#
| Decorator | Where | Purpose |
|---|---|---|
@property, @classmethod, @staticmethod |
built-in | class features |
@dataclass |
dataclasses | auto-generate class methods |
@lru_cache |
functools | caching |
@app.route("/") |
Flask | map a URL to a function |
@login_required |
Flask/Django | require login |
@pytest.fixture |
pytest | test setup |
Summary#
- A closure is an inner function that remembers variables from its enclosing function.
- A decorator takes a function and returns a wrapper that adds behaviour.
@decoratorabovedef fmeansf = decorator(f).- Use
*args, **kwargs, return the result, and apply@wraps(func). - Common uses: logging, timing, access control, validation, caching.