Skip to content
Kuza Ndoto Academy

Decorators

Beginner → IntermediateChapter 9 · Page 48 of 564 min readUpdated 15 Nov 2026

A decorator is a function that wraps another function to add extra behaviour, such as logging, timing or checking permissions, without changing the original function's code. You apply one by writing @decorator_name above a function.

Functions are objects

Decorators rely on three facts about Python functions: you can store them in variables, pass them to other functions, and define them inside other functions.

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

yell = shout                     # store a function in a variable
print(yell("habari"))

def apply_twice(func, value):    # pass a function as an argument
    return func(func(value))

print(apply_twice(lambda x: x * 3, 2))

def make_multiplier(n):          # return a function from a function
    def multiply(x):
        return x * n
    return multiply

double = make_multiplier(2)
print(double(21))
HABARI! 18 42

The inner function multiply remembers n even after make_multiplier has finished. A function that remembers values from the place it was created is called a closure, and decorators are built from closures.

Your first decorator

A decorator takes a function, defines a new wrapper function that does something extra around it, and returns the wrapper.

def announce(func):
    def wrapper():
        print("About to run", func.__name__)
        func()
        print("Finished", func.__name__)
    return wrapper

@announce
def greet():
    print("Hello from Kuza Ndoto")

greet()
About to run greet Hello from Kuza Ndoto Finished greet

The @announce line is shorthand. It means exactly the same as writing greet = announce(greet) after the function definition. From then on, the name greet refers to the wrapper.

greet() your call wrapper (built by @announce) 1. print "About to run" 2. call the original greet 3. print "Finished" after decoration, the name greet points to this wrapper
Figure 1. The decorator doesn't change the original function; it hides it inside a wrapper. Every call goes through the wrapper, which adds behaviour before and after.

Decorating functions that take arguments

A useful decorator should work with any function, whatever its arguments and return value. Use *args and **kwargs to pass everything through, and return the original result.

import functools

def log_call(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

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

add(3, 4)
add(2, b=10)
print(add.__name__, "-", add.__doc__)
Calling add with (3, 4) {} add returned 7 Calling add with (2,) {'b': 10} add returned 12 add - Add two numbers.

@functools.wraps(func) copies the original function's name, docstring and other details onto the wrapper. Without it, add.__name__ would be "wrapper", which makes debugging and help() confusing. Always use it.

Common mistake

Forgetting return result in the wrapper. The decorated function then always returns None, even though the original returns a value. Another frequent slip is writing @log_call() with brackets for a decorator that doesn't take arguments.

A practical decorator: timing

import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {elapsed:.4f} seconds")
        return result
    return wrapper

@timer
def total_up_to(n):
    return sum(range(n + 1))

print(total_up_to(1_000_000))

The timing depends on your computer, so your number will differ:

total_up_to took 0.0123 seconds 500000500000

Decorators that take arguments

To write @repeat(3), you need one more layer: a function that takes the argument and returns a decorator.

import functools

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 cheer(team):
    print(f"Go {team}!")

cheer("Harambee Stars")
Go Harambee Stars! Go Harambee Stars! Go Harambee Stars!

Stacking decorators

You can apply several decorators. The one closest to the function is applied first, so the outer one wraps everything.

def stars(func):
    def wrapper():
        return "**" + func() + "**"
    return wrapper

def underscores(func):
    def wrapper():
        return "_" + func() + "_"
    return wrapper

@stars
@underscores
def word():
    return "kuza"

print(word())     # same as stars(underscores(word))()
**_kuza_**

Decorators you'll meet

DecoratorWhat it does
@propertyTurns a method into an attribute-like value (Encapsulation)
@classmethod, @staticmethodSpecial kinds of methods (Methods & Attributes)
@dataclassGenerates __init__, __repr__ and more for a class
@functools.cacheRemembers results so repeated calls are instant
@contextlib.contextmanagerBuilds a context manager from a generator (Context Managers)
@app.route("/") and similarWeb frameworks like Flask use decorators to connect URLs to functions

functools.cache shows how powerful decorators can be. The slow recursive Fibonacci function becomes instant, because each value is calculated only once:

from functools import cache

@cache
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(80))
23416728348467685

Without @cache, this recursive function would make trillions of calls and effectively never finish.

Key points

  • A decorator is a function that takes a function and returns a new, wrapped function.
  • @deco above def f means f = deco(f).
  • Use *args, **kwargs, return the result, and add @functools.wraps(func).
  • Decorators with arguments need an extra outer function.
Up next · Intermediate PythonContext ManagersThe with statement explained.
→

Tip: use the ← and → keys to move between pages.