Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 63 of 70

Python decorators: wrapping functions

Learn how decorators wrap functions to add behaviour, write your own with @ syntax, keep function names with functools.wraps, and pass arguments to a decorator.

14 minGoing furtherUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite a decorator that adds behaviour around a function, apply it with the @ syntax, and use functools.wraps and decorator arguments correctly.

After this lesson you will be able to read the @something lines that appear above functions, and write your own decorators to add behaviour such as logging or counting calls without changing the function itself. You need to be comfortable with functions, *args and **kwargs and returning functions from functions.

Functions are values

A decorator relies on one idea: in Python a function is an ordinary value. You can store it in a variable, pass it to another function, and return it from one.

python
def greet(name):
    return "Hello, " + name

say = greet
print(say("Asha"))

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

print(run_twice(str.upper, "ok"))
result
Hello, Asha
OK

A decorator by hand

A decorator is a function that receives a function, builds a new function that wraps the old one, and returns the new one. Here is one that announces every call.

python
def announce(func):
    def wrapper(*args, **kwargs):
        print("calling", func.__name__)
        result = func(*args, **kwargs)
        print("finished", func.__name__)
        return result
    return wrapper

def total_price(price, count):
    return price * count

total_price = announce(total_price)
print(total_price(4, 3))
result
calling total_price
finished total_price
12

The name total_price now points to wrapper. When you call it, the wrapper prints a message, calls the original function with the same arguments, prints another message and passes the result back.

The @ syntax

Reassigning by hand is clumsy, so Python offers a shortcut. Placing @announce above a function definition means exactly total_price = announce(total_price).

python
@announce
def total_price(price, count):
    return price * count

print(total_price(5, 2))
print(total_price(price=2, count=10))
result
calling total_price
finished total_price
10
calling total_price
finished total_price
20

Because the wrapper takes *args and **kwargs and forwards them, the decorator works for any function, whatever its parameters. The wrapper also returns the result of the original call, so do not forget that line.

Keeping the original name with functools.wraps

There is a catch. After decoration the function reports the name of the wrapper, and its docstring is gone.

python
@announce
def apply_tax(amount):
    """Add 20 percent tax."""
    return amount * 1.2

print(apply_tax.__name__)
print(apply_tax.__doc__)
result
wrapper
None

Tools that show help or log function names would be confused. The standard fix is functools.wraps, itself a decorator, which copies the name and docstring onto the wrapper.

python
from functools import wraps

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

@announce
def apply_tax(amount):
    """Add 20 percent tax."""
    return amount * 1.2

print(apply_tax.__name__)
print(apply_tax.__doc__)
print(apply_tax(100))
result
apply_tax
Add 20 percent tax.
calling apply_tax
120.0

Add @wraps(func) to every wrapper you write. It is a good habit.

A decorator that remembers things

A wrapper can keep state, such as counting how many times a function was called. Attributes on the wrapper function are a simple place to store it.

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

@count_calls
def borrow(title):
    return "Borrowed " + title

borrow("Dune")
borrow("Emma")
print(borrow.calls)
result
2

Decorators with arguments

What if you want @repeat(3)? Then repeat(3) must itself return a decorator. That is three levels: the outer function takes the setting, the middle one takes the function, and the inner one is the wrapper.

python
def repeat(times):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            result = None
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

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

cheer("Ben")
result
Go Ben
Go Ben
Go Ben

Stacking decorators

Several decorators can be stacked. The one nearest the function wraps it first.

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

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

@bold
@italic
def label(text):
    return text

print(label("sale"))
result
<b><i>sale</i></b>

Decorators you already have

The standard library is full of them. functools.lru_cache remembers the results of earlier calls, which can make repeated work far cheaper.

python
from functools import lru_cache

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

print(fib(30))
print(fib.cache_info())
result
832040
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)

In the object-oriented lessons you will also meet @staticmethod, @classmethod and @property, which are decorators too.

Common mistakes

  • Forgetting to return the wrapper. If the decorator does not end with return wrapper, the decorated name becomes None.
  • Forgetting to return the result. If the wrapper calls func(...) but does not return it, the decorated function always gives back None.
  • Leaving out *args and **kwargs. The decorator then works for only one function shape.
  • Skipping functools.wraps. Everything works, but names and docstrings are wrong in help and error messages.
  • Writing @repeat instead of @repeat(3). When a decorator takes arguments you must call it with brackets.

Exercise

Write a decorator shout that makes a function's returned text upper case. Apply it to a function welcome(name) that returns "welcome, " + name, and print the result for "Asha". Check that welcome.__name__ is still welcome.

Show one possible answer
python
from functools import wraps

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

@shout
def welcome(name):
    return "welcome, " + name

print(welcome("Asha"))
print(welcome.__name__)
result
WELCOME, ASHA
welcome

Next: context managers and with is another way of adding set-up and clean-up around code. A video version of this topic is in the video course at /learn/python/.

Key points

  • A decorator is a function that takes a function and returns a new function, usually one that wraps the original.
  • The line @decorator above a def is shorthand for name = decorator(name).
  • Inside the wrapper, accept *args and **kwargs and pass them on, so the decorator works with any function.
  • Add functools.wraps(func) to the wrapper so the decorated function keeps its name and docstring.
  • To give a decorator its own settings, write a function that returns the decorator, as in @repeat(3).

Check yourself

1. What does the line @shout above def greet(): ... do?
2. Why should a wrapper accept *args and **kwargs?
3. What problem does functools.wraps solve?
4. How many nested functions does a decorator that takes its own argument, such as @repeat(3), usually have?