Skip to contentSkip to navigation

Module 14 · Lesson 01

Decorators

Wrap extra behaviour around functions without changing them: functions as objects, closures, the @ syntax, wrappers with *args and **kwargs, functools.wraps, decorators with arguments and stacking.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Functions as values
  • Write a first decorator
  • Wrappers for any arguments
  • Watch a decorator wrap a function

Wrap a function, keep it unchanged

A decorator takes a function and gives back a new one that adds something before or after it.

  • Functions are values

    Store a function in a name, or hand it to another function, like any value.

  • The wrapper

    An inner function calls the original, with extra work around the call.

  • The @ line

    @timer above a def means f = timer(f) straight after it.

  • functools.wraps

    Copies the name and docstring, so the wrapped function still looks like itself.

Decorators everywhere

Frameworks use decorators to add behaviour with a single line.

  • Web pages@app.route("/home") tells a web framework which function answers a page.
  • Caching@functools.cache remembers answers, so slow work runs only once.
  • LoggingWrite a line to a log every time a function is called.
  • Sign-in checks@login_required turns away anyone who is not signed in.

The line every wrapper needs

Inside a wrapper, this line calls the original function. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

result:The original's answer. The wrapper should return it, or every call gives None.

Wrap functions with decorators

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Functions are values

A function is an object: give it another name, or pass it to another function.

Your turn: Write a whisper function that lower-cases text, and pass it to apply.

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

def apply(func, value):
    return func(value)

speak = shout
print(speak("hi"))
print(apply(shout, "hey"))
print(apply(len, "hey"))
Output
Press Run to see what it prints.

Watch a decorator wrap a function

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. def bold(func):
  2. def wrapper(text):
  3. return "**" + func(text) + "**"
  4. return wrapper
  5. @bold
  6. def title(text):
  7. return text.title()
  8. print(title("hello world"))
  9. print(title.__name__)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.When does the decorator run?

def deco(func):
    print("decorating", func.__name__)
    return func

@deco
def hi():
    print("hi")

print("done")

0 of 6 answered

Common decorator misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Functions are values

In Python a function is an object like any other. You can give it another name, put it in a list, pass it to another function or return it from one:

Try it 1: edit me, then Run
def shout(text):
    return text.upper() + "!"

speak = shout                 # no brackets: the function itself
print(speak("hi"))            # HI!

def apply_twice(func, value):
    return func(func(value))

print(apply_twice(shout, "hey"))   # HEY!!
Output
Press Run to see what it prints.

Writing a name without brackets refers to the function; adding brackets calls it. Decorators rely entirely on that difference.

Inner functions and closures

A function can define another function inside itself and return it:

Try it 2: edit me, then Run
def make_greeter(greeting):
    def greet(name):
        return f"{greeting}, {name}"
    return greet

hello = make_greeter("Hello")
print(hello("Ana"))           # Hello, Ana
Output
Press Run to see what it prints.

make_greeter has already finished when hello("Ana") runs, yet greet still knows greeting. An inner function that remembers variables from the function around it is a closure. Every decorator is built from one.

A first decorator

A decorator is a function that takes a function and returns a new function, usually one that does something extra and then calls the original:

Try it 3: edit me, then Run
def announce(func):
    def wrapper():
        print("about to call", func.__name__)
        return func()
    return wrapper

def tidy():
    print("tidying up")

tidy = announce(tidy)
tidy()       # about to call tidy, then tidying up
Output
Press Run to see what it prints.

The line tidy = announce(tidy) replaces tidy with the wrapper, which remembers the original in func. Python has special syntax for exactly that line. Writing @announce above the definition means the same thing:

Try it 4: edit me, then Run
@announce
def tidy():
    print("tidying up")
Output
Press Run to see what it prints.

The decorator runs once, when the function is defined. The wrapper runs every time the function is called.

Wrappers for any arguments

The wrapper above only works for functions without parameters. To wrap any function, accept every argument with *args and **kwargs and pass them all on, and return whatever the original returns:

Try it 5: edit me, then Run
def logged(func):
    def wrapper(*args, **kwargs):
        print(f"{func.__name__} called with {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

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

add(2, b=3)
Output
Press Run to see what it prints.

Forgetting return result is the most common decorator bug: the decorated function then returns None however good the original was.

Keeping the name: functools.wraps

After decorating, add.__name__ is "wrapper" and the docstring is gone, which confuses error messages, help() and debugging tools. The standard fix is one more decorator, from functools, on the wrapper:

Try it 6: edit me, then Run
import functools

def logged(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper
Output
Press Run to see what it prints.

functools.wraps(func) copies the name, docstring and other details of func onto the wrapper. Make it a habit in every decorator you write.

Decorators that take arguments

Sometimes the decorator itself needs settings, as in @repeat(3). Then you need one more level: a function that takes the settings and returns a decorator:

Try it 7: edit me, then Run
def repeat(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def ping():
    print("ping")
Output
Press Run to see what it prints.

Read @repeat(3) as two steps: repeat(3) runs first and returns decorator, and then decorator is applied to ping. Three nested functions look busy, but each has one job: keep the settings, keep the function, do the work.

Stacking decorators

Several decorators can sit above one function:

Try it 8: edit me, then Run
@bold
@italic
def title():
    return "News"
Output
Press Run to see what it prints.

They apply from the bottom up: title = bold(italic(title)). When title() is called, bold's wrapper runs first and calls italic's wrapper, which calls the original. So the decorator nearest the function is the innermost layer.

Decorators you get for free

Python and its standard library include useful decorators. functools.cache remembers the result for each set of arguments, so a slow function is computed only once per input. @property, @classmethod and @staticmethod change how methods in a class behave; they come later in this course. Frameworks add many more, such as one that connects a web address to a function. They all follow the same rule you now know: take a function, return a replacement.

Syntax

The general shape of the statements in this lesson.

syntax.py
import functools

def decorator(func):
    @functools.wraps(func)            # keep name and docstring
    def wrapper(*args, **kwargs):
        # before
        result = func(*args, **kwargs)
        # after
        return result                 # pass the result back
    return wrapper

@decorator                            # same as f = decorator(f)
def f(x): ...

def factory(setting):                 # decorator with arguments
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    return decorator

@factory(3)                           # f = factory(3)(f)
def g(): ...

@outer                                # stacked: h = outer(inner(h))
@inner
def h(): ...
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Counting and logging calls

Beginner

Write a decorator that counts how many times a function has been called and prints the count and the result on every call. Apply it to a discount function and check that its name survives.

Python
import functools

def counted(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        result = func(*args, **kwargs)
        print(f"call {wrapper.calls}: {func.__name__}{args} -> {result}")
        return result
    wrapper.calls = 0
    return wrapper

@counted
def discount(price, percent):
    """Price after a percentage discount."""
    return round(price * (1 - percent / 100), 2)

discount(80, 25)
discount(19.99, 10)
print(discount.__name__, "|", discount.__doc__, "|", discount.calls, "calls")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Functions are objects, so the wrapper can carry its own calls attribute, set to 0 when the decorator runs. Each call increases it before calling the original. Thanks to functools.wraps, discount keeps its real name and docstring even though it is now the wrapper.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Forgetting to return the result

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
def logged(func):
    def wrapper(*args):
        print('calling', func.__name__)
        func(*args)
    return wrapper

@logged
def square(n):
    return n * n

print(square(4))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints calling square, then None instead of 16

Write this instead

def logged(func):
    def wrapper(*args):
        print('calling', func.__name__)
        return func(*args)
    return wrapper

@logged
def square(n):
    return n * n

print(square(4))

Why it happens

The wrapper calls the original but throws its return value away, so the wrapper returns None.

In the real world

Where this shows up in software people use every day.

  1. Role checks on web handlers

    Web applications

    An internal admin site has many handler functions, and some may only be used by certain roles. Instead of repeating the same if statement at the top of each handler, the team writes one decorator factory and marks each handler with the role it needs.

    Why Python fits

    The rule lives in one place, and each handler states its requirement in a single readable line. The wrapper checks the role before the handler body ever runs, and functools.wraps keeps each handler's real name for the error message. Adding a new protected handler needs no new checking code at all.

    Python
    import functools
    
    class Forbidden(Exception):
        pass
    
    def requires(role):
        def decorator(handler):
            @functools.wraps(handler)
            def wrapper(user, *args, **kwargs):
                if role not in user["roles"]:
                    raise Forbidden(f"{user['name']} needs {role} for {handler.__name__}")
                return handler(user, *args, **kwargs)
            return wrapper
        return decorator
    
    @requires("admin")
    def delete_account(user, account_id):
        return f"account {account_id} deleted by {user['name']}"
    
    @requires("support")
    def view_ticket(user, ticket_id):
        return f"ticket {ticket_id} shown to {user['name']}"
    
    ana = {"name": "ana", "roles": {"admin", "support"}}
    ben = {"name": "ben", "roles": {"support"}}
    
    for call in [lambda: delete_account(ana, 7), lambda: view_ticket(ben, 31), lambda: delete_account(ben, 8)]:
        try:
            print(call())
        except Forbidden as error:
            print("403:", error)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

When does the decorator code run?

The decorator itself runs once, when Python reaches the decorated def, usually as the module loads. Only the wrapper runs on each call. That is why a print in the decorator, outside the wrapper, appears even if the function is never called.

Can I decorate a method in a class?

Yes. The wrapper receives self as the first item of args, so a *args, **kwargs wrapper works for methods unchanged.

How do I undo a decorator to test the original function?

If the decorator used functools.wraps, the original is available as decorated.__wrapped__. That is another good reason to always use wraps.

Should I write my own caching decorator?

Usually not. functools.cache and functools.lru_cache(maxsize=...) are tested, fast and handle arguments correctly. Write your own only to learn, or when you need special behaviour such as expiring old entries.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/2 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 23 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.