⚡0 XP🔥0

Decorators

Lesson 31 of 33 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Understand closures and decorators - functions that wrap other functions to add logging, timing, validation or access checks - with @syntax, arguments and functools.wraps.

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:

▶ Try it YourselfPython
Ctrl + Enter to run

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:

  1. takes a function as input,
  2. defines a wrapper function that adds some behaviour before/after calling the original,
  3. returns the wrapper.
▶ Try it YourselfPython
Ctrl + Enter to run

Step 3: the @ syntax#

Writing @decorator above a function does exactly the same as func = decorator(func):

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

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:

▶ Try it YourselfPython
Ctrl + Enter to run

Preserving the function's identity: functools.wraps#

Without care, the decorated function "forgets" its name and docstring:

▶ Try it YourselfPython
Ctrl + Enter to run
Tip

Always use @wraps(func) in your decorators - debugging tools, documentation and frameworks rely on the original name.

Practical decorators#

Timing a function#

▶ Try it YourselfPython
Ctrl + Enter to run

Access control (like a login check in web apps)#

▶ Try it YourselfPython
Ctrl + Enter to run

This is exactly how Flask's @login_required and Django's @permission_required work.

Caching results (memoisation)#

Python has a built-in caching decorator:

▶ Try it YourselfPython
Ctrl + Enter to run

Decorators with their own arguments#

To pass arguments to the decorator itself (like @repeat(3)), add one more level:

▶ Try it YourselfPython
Ctrl + Enter to run

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.
  • @decorator above def f means f = decorator(f).
  • Use *args, **kwargs, return the result, and apply @wraps(func).
  • Common uses: logging, timing, access control, validation, caching.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Uppercase decorator

Write a decorator uppercase that converts the string returned by the decorated function to upper case.

Expected output:
HELLO ASHA
2

Call counter

Write a decorator count_calls that keeps track of how many times the function was called, in an attribute calls on the wrapper (wrapper.calls).

3

Positive arguments only

Write a decorator positive_only that raises ValueError("Arguments must be positive") if any positional argument is ≤ 0; otherwise it calls the function normally.

Quick Quiz

Q1.

What is a decorator?

Q2.

@my_decorator above def greet(): is the same as...

Q3.

Why do wrappers usually accept *args, **kwargs?

Q4.

What does functools.wraps do?

Q5.

What is a closure?