Thuta Learning
Python
AdvancedProgrammingBeginner

Decorators (In Depth)

PythonLesson 4225 min

What you'll walk away with

  • Show that a function can be stored in a variable, passed as an argument and returned
  • Write a wrapper that accepts *args and **kwargs and returns the original result
  • Explain that an @decorator line is the same as func = decorator(func)
  • Explain why functools.wraps keeps __name__, __doc__ and __wrapped__ intact

Explain it simply

Explain it simply

Think of wrapping a present. The gift inside does not change, but the wrapping adds something extra to the moment it is opened. A Python decorator works the same way: it puts a layer around an existing function without editing the function itself.

That layer can do work before the function runs and after it finishes, such as writing a log line, measuring time or checking a permission. You get the extra behaviour by adding a single line like @log above the function, and the body stays exactly as it was.

Problem → Why → Solution

The problem: logging code pasted into every function

Say you want to know when each function is called and what it returns, so you add print lines inside every function. With two functions that is fine. With twenty functions you have forty copied print lines, and changing the format means editing twenty places. Put the return before the print by accident and the "after" line never appears at all.

orders.py
def add_item(cart, item):
    print("calling add_item")          # copied
    cart.append(item)
    print("add_item finished")         # copied
    return cart

def total(cart):
    print("calling total")             # copied again
    return sum(cart)
    print("total finished")            # never runs: after return

Why is this a problem?

Logging is not the main job of any one function; it is a cross-cutting concern that runs across many of them. Copying it everywhere mixes it into the business logic and multiplies mistakes. A decorator lets you write that code once and wrap every function from the outside.

Core concept: take a function, return a new function

To understand decorators you first need one fact: in Python, functions are first-class objects. Writing def shout(text): ... builds a function object and binds it to the name shout. Writing yell = shout gives that same object a second name. You can pass a function to another function as an argument and return a function from inside a function. A function that accepts or returns another function is called a higher-order function.

A decorator is a higher-order function that takes a function and returns a new one. Inside, it defines an inner function, usually called wrapper, that does the extra work and calls the original. The wrapper can still reach func, the decorator's parameter, because of a closure: an inner function keeps the variables of the scope that created it, even after the decorator has returned.

To wrap any function at all, the wrapper is written as def wrapper(*args, **kwargs). *args collects every positional argument into a tuple, **kwargs collects every keyword argument into a dict, and func(*args, **kwargs) spreads them back out unchanged. The wrapper must also return func's result, otherwise every decorated function suddenly returns None.

Writing @announce above def greet(...) is exactly the same as greet = announce(greet). It happens once, when the function is defined, not on every call. From then on the name greet points at the wrapper, so every greet() call runs the wrapper. That swap is why greet.__name__ becomes "wrapper" and the docstring disappears. Adding @functools.wraps(func) on the wrapper copies the original __name__, __doc__ and other metadata onto it, and also stores the original in a __wrapped__ attribute.

Mental model: the name is re-pointed at the wrapper
  1. def builds the function object
  2. @deco calls deco(func) once
  3. The name now points at wrapper
  4. Each call: wrapper -> func -> wrapper

The decorator runs once at definition time; the wrapper runs on every call.

General pattern

python
import functools
def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # work before the call
        result = func(*args, **kwargs)
        # work after the call
        return result
    return wrapper

@decorator
def target(...): ...

The decorator receives func and returns wrapper. The wrapper forwards every argument and hands back the result, and @functools.wraps(func) keeps the original name and docstring.

Example: a decorator that announces every call

The announce decorator prints each call's arguments and its return value. The first part decorates by hand without @, the second does the same thing with the @ syntax, and the last two lines show what functools.wraps preserved.

announce.py
import functools


def announce(func):
    """Print one line before and one line after every call."""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        parts = [repr(a) for a in args]
        parts += [f"{k}={v!r}" for k, v in kwargs.items()]
        print(f"-> {func.__name__}({', '.join(parts)})")
        result = func(*args, **kwargs)
        print(f"<- {func.__name__} returned {result!r}")
        return result
    return wrapper


def multiply(a, b):
    return a * b

# 1. Decorating by hand: pass the function in, keep what comes back
multiply = announce(multiply)
print("result:", multiply(3, 4))

# 2. The @ line does exactly the same thing, at definition time
@announce
def greet(name, greeting="Hello"):
    """Build a friendly greeting."""
    return f"{greeting}, {name}!"

print("result:", greet("Sai", greeting="Hi"))

# 3. functools.wraps copied the original name and docstring
print(greet.__name__, "|", greet.__doc__)
print(greet.__wrapped__("Aye"))

Code breakdown

  1. Line 6-7def wrapper(*args, **kwargs):

    The wrapper accepts any number of arguments, so one decorator can wrap both multiply, with two positional parameters, and greet, with a keyword argument. The @functools.wraps(func) line above it copies the metadata.

  2. Line 11-13result = func(*args, **kwargs)

    This calls the original function, remembered through the closure, with the arguments spread back out unchanged. Saving the result in a variable lets the wrapper print the "<-" line first and only then return result.

  3. Line 21multiply = announce(multiply)

    This is decoration without @. announce returns the wrapper, and the name multiply is re-pointed at it. The original function lives on inside the wrapper's closure.

  4. Line 25-26@announce

    As soon as def greet finishes, Python runs greet = announce(greet) automatically. It is the same work as line 21, just written where readers see it, right above the function.

  5. Line 33-34print(greet.__wrapped__("Aye"))

    Because of wraps, __name__ is "greet" instead of "wrapper" and the docstring survives. __wrapped__ is the undecorated greet, so calling it prints only Hello, Aye! with no "->" lines.

You should see
-> multiply(3, 4)
<- multiply returned 12
result: 12
-> greet('Sai', greeting='Hi')
<- greet returned 'Hi, Sai!'
result: Hi, Sai!
greet | Build a friendly greeting.
Hello, Aye!
What happens on greet("Sai", greeting="Hi")
  1. The name greet is the wrapper, so the wrapper runs
  2. args is ('Sai',) and kwargs is {'greeting': 'Hi'}
  3. The "->" line is printed
  4. The original greet is called and returns 'Hi, Sai!'
  5. The "<-" line is printed and the result goes back to the caller

Decorators that ship with Python

You have probably used decorators before writing one. Inside a class, @property lets a method be read like an attribute, @staticmethod makes a method that needs no self, and @classmethod makes one that receives the class instead of an instance. functools.cache remembers results for arguments it has already seen. All of them follow the rule above: at definition time they take an object and return a replacement.

builtin_decorators.py
import functools


class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):
        return round(3.14159 * self.radius ** 2, 2)

    @staticmethod
    def unit_name():
        return "cm"


@functools.cache
def slow_square(n):
    print(f"  computing {n}...")
    return n * n


print(Circle(2).area, Circle.unit_name())
print(slow_square(9), slow_square(9))

A timing decorator: measure without touching the result

Timing is one of the most common decorator examples. Use time.perf_counter() rather than time.time(): perf_counter is a high-resolution clock meant for measuring durations and is not affected by system clock changes. Putting the measurement in try/finally means the duration is printed even when the function raises, and the exception still propagates afterwards. The duration varies slightly on every run, so never expect an exact number in the output.

timing.py
import functools
import time


def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            elapsed = time.perf_counter() - start
            print(f"{func.__name__} took {elapsed:.3f}s")
    return wrapper


@timed
def nap():
    time.sleep(0.05)
    return "rested"


print(nap())  # e.g. "nap took 0.051s" then "rested"

In real projects

Where this shows up in real projects

Web frameworks are the heaviest users of decorators. In Flask, @app.route("/users") connects a URL to a function, and in Django @login_required redirects anonymous users before they ever reach the view. pytest's @pytest.fixture and the @dataclass decorator from dataclasses are decorators too. In each case your function body does only its main job, and the decorator handles the shared work such as routing, authentication or setup.

In your own projects, retries, caching, timing, permission checks and audit logs are commonly written as decorators. This is where functools.wraps really matters: Flask takes the endpoint name from the function's __name__, so using a decorator without wraps on two routes gives both the same name, "wrapper", and Flask raises an error about an overwritten endpoint. Logging, profilers and documentation tools also depend on the original name and docstring.

Common mistakes

Common mistakes

1. Forgetting the return inside the wrapper

If the wrapper calls func(*args, **kwargs) but does not return the result, every decorated function returns None. total = add(2, 3) quietly becomes None instead of 5, with no error to point you at the cause. Always save result = func(...) and end the wrapper with return result.

2. Hard-coding the wrapper's parameters

A def wrapper(): signature can only wrap functions that take no arguments. Calling add(2, 3) fails with "wrapper() takes 0 positional arguments but 2 were given". Accept *args, **kwargs and spread them into func the same way.

3. Calling the decorator on the @ line

Writing @announce() with parentheses calls announce with no arguments first and uses the result as the decorator. announce needs its func parameter, so you get "missing 1 required positional argument: 'func'". Plain decorators are written @announce without parentheses; the parenthesised form is for decorator factories that take arguments.

4. Leaving out functools.wraps

Without wraps, every decorated function reports __name__ as "wrapper" and help() shows no docstring. Tracebacks, logs and framework registrations can no longer tell the functions apart. Make @functools.wraps(func) on every wrapper a habit.

Best practices

Best practices

  • Keep each decorator to one job (log, time, check) and never hide a function's business logic inside a decorator.
  • Pass arguments and the return value through unchanged; if a decorator must alter them, make that obvious in its name.
  • In tests, reach the undecorated logic through __wrapped__ when you only want to check the original behaviour.

Mini challenge

Mini challenge: a call-counting decorator

Write a count_calls decorator that records how many times a function has been called, and apply it to two functions. Each function must keep its own counter.

  • Store the counter in a wrapper.calls attribute (no global variable)
  • The wrapper accepts any arguments and returns the original result
  • Keep __name__ and __doc__ with functools.wraps
  • Call square four times and shout once, then print both counters
count_calls.py
import functools


def count_calls(func):
    # TODO: define a wrapper that preserves func's metadata
    # TODO: increase the wrapper's own calls counter, then call func
    # TODO: start the counter at 0 before returning the wrapper
    ...


@count_calls
def square(n):
    """Return n squared."""
    return n * n


# TODO: decorate a shout(text) function that upper-cases text and adds "!"
# TODO: call square for 1..4 and shout once, then print each name and count

Expected: [1, 4, 9, 16] HELLO! square: 4 calls (Return n squared.) shout: 1 call

Show hint

Functions are objects, so they can carry attributes. After defining the wrapper and before returning it, write wrapper.calls = 0; inside the wrapper, wrapper.calls += 1 works.

Show solution
count_calls.py
import functools


def count_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return func(*args, **kwargs)
    wrapper.calls = 0
    return wrapper


@count_calls
def square(n):
    """Return n squared."""
    return n * n


@count_calls
def shout(text):
    return text.upper() + "!"


print([square(n) for n in range(1, 5)])
print(shout("hello"))
print(f"{square.__name__}: {square.calls} calls ({square.__doc__})")
print(f"{shout.__name__}: {shout.calls} call")

Quick quiz 1 / 3

Writing @announce above def greet(): ... is equivalent to what?

Quick quiz 2 / 3

A wrapper is written as def wrapper(*args): print("calling"); func(*args), with no return. If add(a, b) returns a + b, what does print(add(2, 3)) show?

Quick quiz 3 / 3

If report() is decorated by a decorator without functools.wraps, what is report.__name__?

What to remember

  • Functions are objects: you can pass them, return them and attach attributes to them.
  • A decorator takes func and returns a wrapper that remembers func through a closure.
  • @decorator runs func = decorator(func) once, at definition time.
  • A wrapper accepts *args, **kwargs, returns the result, and always carries @functools.wraps(func).

Python Documentation — Functional Programming HOWTO — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Decorators (In Depth) | Thuta Learning