Decorators & Advanced Features

Published by Brayan K

Decorators are one of Python's most powerful features — used in Django, Flask, FastAPI, TensorFlow, PyTorch, logging systems, authentication, caching, and more. This lesson takes you far beyond the basics.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A function that makes another function

*args & **kwargs built a logged() that takes a function and its arguments, prints the call and passes the arguments on. Change it to take only the function, and hand back a new function that does the logging whenever it's called:

def area(width, height, unit="m"):
    return str(width * height) + " " + unit

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

logged_area = logged(area)
print(logged_area(4, 5, unit="cm"))
print(area(2, 3))

# ✅ Expected output:
# calling area (4, 5) {'unit': 'cm'}
# 20 cm
# 6 m

Each call of the outer function makes a new inner function, which keeps its own values:

def make_greeting(word):
    def greet(name):
        return word + ", " + name + "!"
    return greet

hello = make_greeting("Hello")
howdy = make_greeting("Howdy")
print(hello("Ada"))
print(howdy("Ada"))
print(hello.__name__)

# ✅ Expected output:
# Hello, Ada!
# Howdy, Ada!
# greet

@decorator means name = decorator(name), once

logged is a decorator: a function that takes a function and returns a replacement for it. Python has a short way to apply one as you define a function: @ and the decorator's name, on the line above the def.

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

@logged
def area(width, height, unit="m"):
    return str(width * height) + " " + unit

print(area(4, 5, unit="cm"))
print(area(2, 3))

# ✅ Expected output:
# calling area (4, 5) {'unit': 'cm'}
# 20 cm
# calling area (2, 3) {}
# 6 m

@logged above def area means area = logged(area), done straight after the def. From then on the name area refers to the wrapper, which calls the original for you, so every call is logged. Writing the def and then area = logged(area) does exactly the same. The decorator itself runs once, when the def runs, not on every call:

def logged(func):
    print("decorating", func.__name__)
    def wrapper(*args, **kwargs):
        print("calling", func.__name__, args)
        return func(*args, **kwargs)
    return wrapper

print("start")

@logged
def double(n):
    return n * 2

print("defined")
print(double(4))
print(double(5))

# ✅ Expected output:
# start
# decorating double
# defined
# calling double (4,)
# 8
# calling double (5,)
# 10

So a decorator can do its work at definition time, and needn't replace the function at all. This one notes each function down and returns it unchanged, a common way to mark functions so another part of a program can find them:

commands = {}

def command(func):
    commands[func.__name__] = func
    return func

@command
def hello():
    return "Hello!"

@command
def bye():
    return "Goodbye!"

print(list(commands))
print(commands["bye"]())
print(hello())

# ✅ Expected output:
# ['hello', 'bye']
# Goodbye!
# Hello!

@classmethod and @staticmethod are decorators too

Object-Oriented Programming mentioned two decorators that come with Python. @classmethod makes a method that receives the class instead of an object, often used as another way to make objects. @staticmethod makes one that receives neither:

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, fahrenheit):
        return cls((fahrenheit - 32) * 5 / 9)

    @staticmethod
    def is_freezing(celsius):
        return celsius <= 0

boiling = Temperature.from_fahrenheit(212)
print(boiling.celsius)
print(Temperature.is_freezing(-3), Temperature.is_freezing(boiling.celsius))

# ✅ Expected output:
# 100.0
# True False

They work like logged: @classmethod above def from_fahrenheit means from_fahrenheit = classmethod(from_fahrenheit). Leave the line out, and from_fahrenheit is an ordinary function in the class. Called on the class, the 212 goes into cls, and nothing is left for fahrenheit:

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def from_fahrenheit(cls, fahrenheit):
        return cls((fahrenheit - 32) * 5 / 9)

print(Temperature.from_fahrenheit(212).celsius)

# ✅ Expected error:
# TypeError: Temperature.from_fahrenheit() missing 1 required positional argument: 'fahrenheit'

Return the wrapper; don't call it

Whatever the decorator returns is what the name ends up meaning. Forget the return, and the decorator returns None, as any function without one does:

def shout(func):
    def wrapper():
        return func().upper()

@shout
def greet():
    return "hi"

print(greet())

# ✅ Expected error:
# TypeError: 'NoneType' object is not callable

The mistake is in shout, but the error appears where greet() is called, because greet is None now. Add brackets, return wrapper(), and the decorator calls the wrapper once, at the definition, so greet becomes its result, a string:

def shout(func):
    def wrapper():
        return func().upper()
    return wrapper()

@shout
def greet():
    return "hi"

print(greet)
print(greet())

# ✅ Expected output:
# HI

# ✅ Expected error:
# TypeError: 'str' object is not callable

The wrapper takes everything, passes it on and returns the result

The wrapper stands in for the function, so it has to accept whatever the function accepts. A wrapper with no parameters fails as soon as the decorated function is called with an argument:

def shout(func):
    def wrapper():
        return func().upper()
    return wrapper

@shout
def greet(name):
    return "hi " + name

print(greet("Ada"))

# ✅ Expected error:
# TypeError: shout.<locals>.wrapper() takes 0 positional arguments but 1 was given

shout.<locals>.wrapper is the wrapper's full name: wrapper, defined inside shout. Writing def wrapper(*args, **kwargs) and calling func(*args, **kwargs) accepts anything and passes it all on, as *args & **kwargs showed. That works for methods too, since self simply arrives in args. The wrapper must also return what func returns:

def log_call(func):
    def wrapper(*args, **kwargs):
        print("calling", func.__name__, args)
        func(*args, **kwargs)
    return wrapper

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

total = add(2, 3)
print(total)

# ✅ Expected output:
# calling add (2, 3)
# None

add worked out 5, and the wrapper threw it away, so total is None. With the whole pattern in place, a decorator can do real work around any function, such as checking its arguments before the call, whether they come by position or by name. raise and try are from Exception Handling, and functools.wraps, on the line above the wrapper, is explained below:

import functools

def positive_args(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        for value in list(args) + list(kwargs.values()):
            if value <= 0:
                raise ValueError(f"{func.__name__}() needs positive numbers, got {value}")
        return func(*args, **kwargs)
    return wrapper

@positive_args
def area(width, height):
    return width * height

print(area(3, 4))
print(area(width=2, height=5))
try:
    area(-1, 4)
except ValueError as e:
    print("Refused:", e)

# ✅ Expected output:
# 12
# 10
# Refused: area() needs positive numbers, got -1

functools.wraps keeps the function's name and docstring

After decorating, the name greet refers to the wrapper, so asking for its name or docstring gets the wrapper's:

def shout(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()
    return wrapper

@shout
def greet(name):
    """Return a greeting for name."""
    return "hi " + name

print(greet("Ada"))
print(greet.__name__)
print(greet.__doc__)

# ✅ Expected output:
# HI ADA
# wrapper
# None

help(), which prints a function's docstring and parameters, describes the wrapper too:

def shout(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()
    return wrapper

@shout
def greet(name):
    """Return a greeting for name."""
    return "hi " + name

help(greet)

# ✅ Expected output:
# Help on function wrapper in module __main__:
#
# wrapper(*args, **kwargs)

functools.wraps(func), a decorator from the standard library's functools module, copies the name, the docstring and a few other details from func onto the wrapper:

import functools

def shout(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()
    return wrapper

@shout
def greet(name):
    """Return a greeting for name."""
    return "hi " + name

print(greet("Ada"))
print(greet.__name__)
print(greet.__doc__)
help(greet)

# ✅ Expected output:
# HI ADA
# greet
# Return a greeting for name.
# Help on function greet in module __main__:
#
# greet(name)
#     Return a greeting for name.

Use it whenever a decorator returns a wrapper. It has one side effect to know about: error messages use the copied name as well, so a wrapper with no parameters now reports greet() as taking none:

import functools

def shout(func):
    @functools.wraps(func)
    def wrapper():
        return func().upper()
    return wrapper

@shout
def greet(name):
    return "hi " + name

print(greet("Ada"))

# ✅ Expected error:
# TypeError: greet() takes 0 positional arguments but 1 was given

The 0 is the wrapper's count: greet itself takes one argument.

Stacked decorators wrap from the bottom up

Several decorators can sit above one def. The one nearest the def is applied first, and each one above wraps the result:

def bold(func):
    def wrapper(*args, **kwargs):
        return "<b>" + func(*args, **kwargs) + "</b>"
    return wrapper

def italic(func):
    def wrapper(*args, **kwargs):
        return "<i>" + func(*args, **kwargs) + "</i>"
    return wrapper

@bold
@italic
def greet(name):
    return "hi " + name

print(greet("Ada"))

# ✅ Expected output:
# <b><i>hi Ada</i></b>

@bold above @italic means greet = bold(italic(greet)): italic's wrapper goes on first and bold's around it, so bold's tags end up outside. Swap the two lines and it prints <i><b>hi Ada</b></i>. When the function is called, the outermost wrapper starts first and finishes last:

def outer(func):
    def wrapper():
        print("outer: before")
        func()
        print("outer: after")
    return wrapper

def inner_layer(func):
    def wrapper():
        print("inner: before")
        func()
        print("inner: after")
    return wrapper

@outer
@inner_layer
def run():
    print("run")

run()

# ✅ Expected output:
# outer: before
# inner: before
# run
# inner: after
# outer: after

Decorators that take arguments

To give a decorator settings, as in @repeat(3), you need one more layer. repeat(3) is called first, and returns the decorator that then receives the function:

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def cheer(name):
    print("Go,", name)

cheer("Ada")

# ✅ Expected output:
# Go, Ada
# Go, Ada
# Go, Ada

Read @repeat(3) as two steps: three_times = repeat(3) makes a decorator, and cheer = three_times(cheer) applies it. Each layer keeps what it was given: decorator keeps times, and wrapper keeps func. Leave the brackets off, and repeat itself becomes the decorator: it receives the function as times and returns decorator, which becomes cheer. Nothing fails, but calling cheer only builds a wrapper, and runs nothing:

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat
def cheer(name):
    print("Go,", name)

cheer("Ada")
print("done")

# ✅ Expected output:
# done

Empty brackets, @repeat(), call repeat with nothing for times, and stop at the definition with TypeError: repeat() missing 1 required positional argument: 'times'. Brackets on a plain decorator fail the same way: @shout() gives TypeError: shout() missing 1 required positional argument: 'func'.

A decorator with an argument can retry a call that fails. Here the replies come from a list, standing in for a network that times out twice; ConnectionError is Python's built-in error for a failed connection:

import functools

def retry(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ConnectionError as e:
                    print(f"attempt {attempt} failed: {e}")
            raise ConnectionError(f"{func.__name__} failed {times} times")
        return wrapper
    return decorator

replies = ["timeout", "timeout", "ok"]

@retry(3)
def load_data():
    reply = replies.pop(0)
    if reply != "ok":
        raise ConnectionError(reply)
    return "data"

print(load_data())

# ✅ Expected output:
# attempt 1 failed: timeout
# attempt 2 failed: timeout
# data

A decorator that remembers

A wrapper can keep information from one call to the next. Timing each call is the usual example, but times change on every run and every computer, so this decorator counts calls instead. A function is an object, so it can carry an attribute, as the objects in Object-Oriented Programming did:

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 hello():
    print("hello")

hello()
hello()
print(hello.calls)

# ✅ Expected output:
# hello
# hello
# 2

Each decorated function gets a wrapper of its own, so each keeps its own count. A list made in the decorator works too, because append() changes the list without assigning to the name:

import functools

def log_calls(func):
    calls = []
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        calls.append(args)
        print(func.__name__, "call", len(calls), "with", args)
        return func(*args, **kwargs)
    return wrapper

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

print(add(2, 3))
print(add(10, 20))

# ✅ Expected output:
# add call 1 with (2, 3)
# 5
# add call 2 with (10, 20)
# 30

calls = 0 in the decorator with calls += 1 in the wrapper looks simpler, but the first call stops with an UnboundLocalError: assigning to calls inside the wrapper makes it a new name of the wrapper's own. The nonlocal statement fixes that, which Scope: global, nonlocal & LEGB explains. To measure how long code takes, Profiling & Optimising Python Performance covers the tools.

Decorators that come with Python

functools.lru_cache remembers each result, so a recursive function that would otherwise work out the same values hundreds of thousands of times works out each one once:

import functools

@functools.lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(30))
print(fib.cache_info())

# ✅ Expected output:
# 832040
# CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)

Practice: a decorator that logs calls and results

Finish log_calls. Its three blanks are the functools decorator that keeps the name, the star that passes the positional arguments on, and the word that hands the result back. The hints below the code give the three answers in the order the blanks appear.

import functools

def log_calls(func):
    @functools.___(func)
    def wrapper(*args, **kwargs):
        print("->", func.__name__, args)
        result = func(___, **kwargs)
        print("<-", result)
        ___ result
    return wrapper

@log_calls
def add(a, b):
    """Add two numbers."""
    return a + b

print(add(2, 3))
print(add.__name__, "-", add.__doc__)

# 👉 replace ___ with wraps
# 👉 replace ___ with *args
# 👉 replace ___ with return

# ✅ Expected output:
# -> add (2, 3)
# <- 5
# 5
# add - Add two numbers.

Run it before filling anything in, and Python won't start: the third blank stands for a keyword, so the file isn't valid Python yet, and it stops with SyntaxError: invalid syntax.

On your own: a decorator with a minimum

Write a decorator with an argument, at_least(minimum):

Decorate area(width, height), which returns width times height, with @at_least(1). Print area(3, 4) and area(width=2, height=5), catch the errors from area(0, 4) and area(width=5, height=-1) and print each after Refused:, then print area.__name__. If the last line says wrapper, the wraps line is missing.

import functools

# Write at_least(minimum) here, then decorate area(width, height) with @at_least(1).

# your code here
import functools

def at_least(minimum):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for value in list(args) + list(kwargs.values()):
                if value < minimum:
                    raise ValueError(f"{func.__name__}() needs numbers of at least {minimum}, got {value}")
            return func(*args, **kwargs)
        return wrapper
    return decorator

@at_least(1)
def area(width, height):
    return width * height

print(area(3, 4))
print(area(width=2, height=5))
try:
    print(area(0, 4))
except ValueError as e:
    print("Refused:", e)
try:
    print(area(width=5, height=-1))
except ValueError as e:
    print("Refused:", e)
print(area.__name__)

# ✅ Expected output:
# 12
# 10
# Refused: area() needs numbers of at least 1, got 0
# Refused: area() needs numbers of at least 1, got -1
# area

Practice quiz

shout(func) defines def wrapper(): return func().upper(), but has no return line. Below it, @shout sits above def greet(): return "hi". What does print(greet()) do?

  • It stops with TypeError: 'NoneType' object is not callable
  • It prints HI
  • It prints hi
  • It prints None

Answer: It stops with TypeError: 'NoneType' object is not callable. Without return wrapper, shout returns None, so greet is None, and calling None fails at the greet() line.

logged(func) runs print("decorating", func.__name__) and returns func. A program prints "start", then defines hello() under @logged (hello prints "hello"), then calls hello() twice. What does it print?

  • start, hello, hello
  • start, decorating hello, hello, hello
  • decorating hello, start, hello, hello
  • start, decorating hello, hello, decorating hello, hello

Answer: start, decorating hello, hello, hello. The decorator runs once, when the def runs, after start. The two calls only run hello.

shout(func) returns def wrapper(): return func().upper(), a wrapper with no parameters. @shout decorates def greet(name): return "hi " + name. What does print(greet("Ada")) do?

  • It stops with TypeError: shout.<locals>.wrapper() takes 0 positional arguments but 1 was given
  • It prints HI ADA
  • It stops with TypeError: greet() missing 1 required positional argument: 'name'
  • It prints hi Ada

Answer: It stops with TypeError: shout.<locals>.wrapper() takes 0 positional arguments but 1 was given. greet is the wrapper now, and the wrapper takes no arguments. <locals> means wrapper was defined inside shout.

A logged decorator's wrapper prints "calling", the name and args, then runs func(*args, **kwargs), with no return. @logged decorates def add(a, b): return a + b. What does print(add(2, 3)) show?

  • calling add (2, 3), then 5
  • 5
  • calling add (2, 3), then None
  • It stops with a TypeError

Answer: calling add (2, 3), then None. The wrapper calls add but drops its result, and a function without return gives None.

bold wraps a result in <b></b>, and italic in <i></i>. @italic sits above @bold above def greet(name): return "hi " + name. What does print(greet("Ada")) show?

  • <b><i>hi Ada</i></b>
  • <i>hi Ada</i>
  • hi Ada
  • <i><b>hi Ada</b></i>

Answer: <i><b>hi Ada</b></i>. The decorator nearest the def is applied first, so bold goes on first and italic around it: greet = italic(bold(greet)).

repeat(times) returns a decorator whose wrapper calls func times times. A program puts @repeat, with no brackets, above def cheer(name): print("Go,", name), then runs cheer("Ada") and print("done"). What does it print?

  • Go, Ada, then done
  • It stops with TypeError: repeat() missing 1 required positional argument: 'times'
  • done
  • Go, Ada three times, then done

Answer: done. repeat received cheer as times and returned decorator, so cheer("Ada") just built a wrapper and ran nothing.

shout uses @functools.wraps(func) above def wrapper(): return func().upper(), a wrapper with no parameters. @shout decorates def greet(name): return "hi " + name. What does print(greet("Ada")) do?

  • It prints HI ADA
  • It stops with TypeError: greet() takes 0 positional arguments but 1 was given
  • It stops with TypeError: shout.<locals>.wrapper() takes 0 positional arguments but 1 was given
  • It stops with TypeError: greet() missing 1 required positional argument: 'name'

Answer: It stops with TypeError: greet() takes 0 positional arguments but 1 was given. wraps copied greet's name onto the wrapper, so the wrapper's error uses that name. The 0 is the wrapper's count.

shout's wrapper is def wrapper(*args, **kwargs): return func(*args, **kwargs).upper(), with no functools.wraps. @shout decorates def greet(name). What does print(greet.__name__) show?

  • greet
  • shout
  • None
  • wrapper

Answer: wrapper. The name greet now refers to the wrapper, whose name is wrapper. functools.wraps(func) would copy greet's name onto it.

Continue this course

Frequently asked questions

Can I decorate a class?

Yes. A decorator above a class statement receives the class and returns it, or something to replace it. A register decorator that appends cls.__name__ to a list and returns cls, put above class Dog and class Cat, collects ['Dog', 'Cat']. @dataclass is a class decorator that comes with Python, which Data Classes & Advanced Class Patterns covers.

How do I call the original, undecorated function?

With functools.wraps, the wrapper keeps the original as __wrapped__, so greet.__wrapped__("Ada") skips the wrapper. Without wraps there is no __wrapped__, and asking for it raises AttributeError.

Why does a traceback still say wrapper when I used functools.wraps?

wraps copies details such as __name__ and __doc__ onto the wrapper function, but the code that runs is still the wrapper's, and a traceback names the code that ran: greet.__code__.co_name is still "wrapper". You'll see a wrapper line above the line from the original function.

Can I decorate a lambda?

Not with @, which has to sit above a def or a class. A decorator is an ordinary function, though, so you can call it: shout(lambda name: "hi " + name) returns the wrapped lambda.

What are lines like @app.get("/") or @pytest.fixture in other people's code?

Decorators from libraries. @app.get("/") is a decorator with an argument, like @repeat(3): app.get("/") runs first and returns the decorator. Building APIs with FastAPI and Testing with pytest: Fixtures, Parametrisation & Mocks cover those libraries. This site's editor loads pytest when a program imports it, but not FastAPI.

Related lessons