LearnPy Hub
AdvancedAdvancedLesson 21 of 32

Decorators

Watch the ideaA decorator wraps a function
def greet():
    return "hello"
greet()
'hello'

Start with a plain function: greet() returns 'hello'.

1Level 1 · BasicsBasics

A decorator wraps a function to add extra behaviour, such as timing it, logging calls or checking inputs, without changing the function's own code. You'll see decorators everywhere in real Python, like @dataclass, @property and web frameworks' @app.route.

Step 1: functions are values

In Python a function is an object like any other. You can store it in a variable, pass it to another function, and return it from a function:

def shout(text):
    return text.upper()

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

Step 2: a function that builds a function

A function can define an inner function and return it. The inner function remembers the variables around it; this is called a closure.

Step 3: the decorator

def announce(func):
    def wrapper(*args, **kwargs):
        print("Calling", func.__name__)
        result = func(*args, **kwargs)   # run the original
        print("Done")
        return result
    return wrapper

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

@announce above def add is shorthand for add = announce(add). Now every call to add actually runs wrapper, which runs extra code around the original.

*args and **kwargs collect any positional and keyword arguments, so the same decorator works on functions with any parameters.

Keep the function's name: functools.wraps

Without help, the decorated function's name becomes "wrapper". Put @functools.wraps(func) on the wrapper to copy the original name and docstring across. It's good practice in every decorator.

Decorators with arguments

@repeat(3) needs one more layer: a function that takes the argument and returns a decorator. See the last example.

Useful built-in decorators

  • @functools.lru_cache remembers results, so slow recursive functions become fast.
  • @property lets a method be read like an attribute.
  • @staticmethod and @classmethod are for methods that don't need an object.
Key points: functions are values; a decorator takes a function and returns a new one that wraps it; @deco means f = deco(f); use *args, **kwargs and functools.wraps in the wrapper.

See it in actionThe decorator wraps the function

Calling greet() actually runs wrapper(), which calls the original and changes its result.

Step-by-step

Try it yourselfExample 1: Functions are values

Functions can be stored, passed around and returned.

example_1.py
Output appears here
Fill in the blanks

Functions are values

Fill the blank so say refers to the same function as shout and the program prints HI!.

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

say = 
print(say("hi"))

Example 2: A logging decorator

The wrapper runs before and after the original function.

example_2.py
Output appears here
Fill in the blanks

Announce the call

Fill the blanks so the decorator prints Calling add before running the function, then the result 5.

blanks.py
def announce(func):
    def wrapper(*args):
        print("Calling", func.__name__)
        return (*args)
    return 

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

print(add(2, 3))
Fix the bug

The result disappears

The decorated double(4) should print Running and then 8, but it prints None instead of 8. Fix the wrapper.

buggy.py
Your turn

Run it twice

Write a decorator twice that calls the function two times. Decorate hello() (which prints Hello) so calling it once prints Hello twice.

my_code.py

Example 3: Timing a function

A reusable timer you can put on any function.

example_3.py
Output appears here

Example 4: Caching with lru_cache

Plain recursive Fibonacci is very slow for n = 35; with the cache it's instant.

example_4.py
Output appears here
Your turn

Fast Fibonacci

Add @lru_cache so fib(80) finishes instantly, then print it: 23416728348467685.

my_code.py

Example 5: A decorator with an argument

repeat(3) returns the actual decorator. That's the extra layer.

example_5.py
Output appears here

2Level 2 · IntermediatePractical decorators

Most real decorators follow the same shape: run something before, call the original, run something after.

Counting and validating

A decorator can count how often a function runs, check its arguments, or refuse to run it unless a user is logged in. The original function stays focused on its own job.

Stacking decorators

With two decorators, the one closest to def wraps first. @a above @b means f = a(b(f)).

Retry

For things that sometimes fail (network calls), a @retry(times=3) decorator tries again before giving up.

See it in actionThe wrapper runs around the original

Watch the call go into wrapper first, then into greet, then back out.

Step-by-step

Example 6: Stacked decorators and a login check

Swap the order of @count_calls and @require_login and see what changes.

example_6.py
Output appears here

Example 7: Retry a flaky operation

The fake download fails twice, then works on the third try.

example_7.py
Output appears here

3Level 3 · AdvancedClass decorators, decorator classes and registries

Registries

A decorator doesn't have to wrap anything. It can just record the function in a dictionary and return it unchanged. Web frameworks use this for routes (@app.get("/home")) and command-line tools for commands.

Decorators that are classes

Any object with __call__ can be a decorator, and a class can keep state neatly in attributes.

Decorating classes

@dataclass is a class decorator: it receives the class, adds methods and returns it. You can write your own, such as one that adds a __repr__.

Method decorators

@functools.cached_property computes a value once per object; @functools.singledispatch picks an implementation by the argument's type.

Example 8: A command registry

Adding a command is just adding a decorated function.

example_8.py
Output appears here

Example 9: Decorator classes, class decorators and singledispatch

Three different shapes of decorator in one program.

example_9.py
Output appears here
Common mistakeA wrapper that forgets return result makes every decorated function return None. Always return what the original function returned.
Exercise · predict the output

What does this print?

def double(func):
    def wrapper(x):
        return func(x) * 2
    return wrapper

@double
def add_one(x):
    return x + 1

print(add_one(4))
Quick quiz · 5 questions
1. What is @deco above def f(): ... shorthand for?
2. Why do wrappers usually take *args and **kwargs?
3. What does functools.wraps do?
4. Which decorator remembers earlier results to avoid recomputing them?
5. What does print(len) show, without brackets after len?
Ready to practice decorators?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Decorators · LearnPy Hub