Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python as a system
EXPERIMENT 39 / 101

Wrap behaviour, keep the name.

Add a reusable boundary around a function without losing its identity.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

A decorator accepts a callable and returns a callable, commonly to add behaviour before or after a call. The @ syntax applies that transformation at definition time. A careful wrapper forwards positional and keyword arguments, returns the underlying result, and preserves metadata using functools.wraps.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

decorators.py
from functools import wraps

def announce(function):
    @wraps(function)
    def wrapped(*args, **kwargs):
        print(f"Running {function.__name__}")
        return function(*args, **kwargs)
    return wrapped

@announce
def add(a, b):
    return a + b

print(add(2, b=5))
print(add.__name__)
↳ EXPECTED OUTPUT
Running add
7
add

03 Under the hood

  1. 1

    @announce is the readable equivalent of add = announce(add) after defining the original function.

  2. 2

    The wrapper forwards both kinds of arguments. Returning the result matters: a wrapper that merely calls function would make every decorated call return None.

  3. 3

    wraps copies metadata and sets __wrapped__, helping documentation and introspection. This synchronous wrapper is not suitable unchanged for an async function; asynchronous wrappers must await their underlying coroutine.

04 Your turn, builder

A SMALL MISSION

Write a decorator that doubles a numeric return value while preserving metadata.

Reveal one possible solution +
one_possible_solution.py
from functools import wraps

def doubled(function):
    @wraps(function)
    def wrapped(*args, **kwargs):
        return 2 * function(*args, **kwargs)
    return wrapped

@doubled
def total(a, b):
    return a + b

print(total(3, 4))

05 Check your signal

QUICK SIGNAL CHECK

Why use wraps in a decorator?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.