Lesson 4 of 5 · Advanced Python · 3 min read · Updated

Decorators

Wrapping a function to add behaviour around it, without changing its code.

A decorator is a function that takes a function and returns a new one that wraps it — doing something before, after, or instead. It is a closure put to work.

python
def shout(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result.upper() + "!"
    return wrapper

@shout
def greet(name):
    return f"hello {name}"

print(greet("kavya"))
Output
HELLO KAVYA!

Example

@shout above def greet is exactly greet = shout(greet) written after it. The name greet now points to the wrapper, which calls the original and changes its result.

A useful decorator

python
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 add(a, b):
    return a + b

add(1, 2)
add(3, 4)
print(add.calls, add.__name__)
Output
2 add

*args, **kwargs let the wrapper accept whatever the original accepts. @functools.wraps(func) copies the original's name and docstring onto the wrapper — without it, add.__name__ would say "wrapper".

Decorators that take arguments

python
import functools

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

@repeat(3)
def cheer():
    print("Go!")

cheer()
Output
Go!
Go!
Go!

Note

@repeat(3) first calls repeat(3), which returns the real decorator. That is why it has three levels of function. You have already used decorators that come with Python: @property, @classmethod, @staticmethod.

@log is written above def save():. What is that the same as?

Try this now

  1. Write a @log decorator that prints the function name and its arguments before each call.
  2. Write a @timer decorator using time.perf_counter() that prints how long a function took.

Create a free account to save your progress, or sign in.