Reading history

Python Decorators Explained With Examples

4 min read 1 views

Learn Python decorators: how @ works, wrapper functions, functools.wraps, decorators with arguments, lru_cache and built-in decorators.

A decorator wraps a function to add behaviour (logging, timing, caching, access checks) without changing the function’s own code. You apply one by writing @name above a def. Decorators look magical at first, but they rest on two plain facts: functions can be passed around like any other value, and a function can define and return another function.

In this lesson you will learn

  • What the @ syntax actually does
  • How to write a decorator with a wrapper function
  • Why functools.wraps matters
  • How to write a decorator that takes arguments
  • Built-in decorators such as lru_cache and property

How a Decorator Works

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("rafi"))

# @shout is the same as: greet = shout(greet)
def plain(name):
    return f"bye {name}"
plain = shout(plain)
print(plain("nila"))

Output

HELLO RAFI!
BYE NILA!
  1. shout receives a function and defines wrapper, which calls the original and changes its result.
  2. shout returns wrapper, the new improved function.
  3. @shout above greet is shorthand for greet = shout(greet), which the second half of the example does by hand.
  4. *args, **kwargs let the wrapper accept whatever arguments the original takes. See Python Functions.

Timing, Arguments and Caching

import functools, time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        value = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {'under' if elapsed < 1 else 'over'} 1 second")
        return value
    return wrapper

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

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

@repeat(2)
def ping():
    print("ping")

print(add(2, 3))
ping()
print(add.__name__)

@functools.lru_cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(60))

Output

add took under 1 second
5
ping
ping
add
1548008755920
  • @functools.wraps(func) copies the original name and docstring onto the wrapper. Without it, add.__name__ would print wrapper.
  • Decorators with arguments need one extra layer: repeat(2) returns the real decorator, which then wraps ping.
  • @functools.lru_cache remembers results. The recursive fib(60) would otherwise make over a trillion calls; with caching it finishes instantly.

Decorators You Will Meet Often

DecoratorPurpose
@propertyTurns a method into an attribute with optional validation (example)
@staticmethodA method that does not need self
@classmethodA method that receives the class (cls) instead of the object
@functools.lru_cacheCaches return values
@dataclassWrites __init__, __repr__ and __eq__ for a class

Common Mistakes

  1. Forgetting to return the wrapper from the decorator, which replaces your function with None.
  2. Forgetting to return the result inside the wrapper, so every call returns None.
  3. Skipping functools.wraps, which breaks debugging and documentation tools.
  4. Writing @repeat without the brackets for a decorator that expects an argument.

Practice Exercises

Exercise 1. Write a @log_call decorator that prints the function’s name before running it.

Show answer
import functools

def log_call(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("Calling", func.__name__)
        return func(*args, **kwargs)
    return wrapper

Exercise 2. In what order do stacked decorators run?

Show answer

With @a above @b above def f, Python builds f = a(b(f)). The decorator nearest the function is applied first; the outermost wrapper runs first when you call f.

Frequently Asked Questions

Can a decorator be applied to a class?

Yes. A class decorator receives the class and returns it (or a replacement). @dataclass is the best-known example.

Are decorators only for functions I write?

No. You can wrap any callable, including functions from libraries, by writing new = decorator(old).

Summary

  • A decorator takes a function and returns a wrapped version.
  • @d above def f means f = d(f).
  • Use functools.wraps to keep the original name and docstring.
  • Add an outer function to accept decorator arguments.
Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *