Monday , November 30 2026
Python decorators: simple and parameterised decorators, functools.wraps, a timing decorator and lru_cache, with tested output.

Python Decorators Explained with Examples

Updated: 29 November 2026Level: IntermediateReading time: about 10 minutesPython 3 · tested

A decorator is a function that wraps another function to add behaviour – logging, timing, caching, access checks – without changing its code. You apply it with the @decorator line above a function. Flask routes (@app.get), @property and @lru_cache are all decorators.

What You Will Learn

  • Functions as objects
  • Write a simple decorator
  • Use functools.wraps
  • A timing decorator
  • Decorators with arguments
  • Built-in decorators like lru_cache

Prerequisites

Python Functions and Lambda.

A Simple Decorator

Example
from functools import wraps

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

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

print(greet("riya"))
print(greet.__name__)
Output
HELLO, RIYA
greet

Explanation: @shout means greet = shout(greet). The wrapper calls the original function and changes its result. *args, **kwargs pass any arguments through. @wraps keeps the original name and docstring – without it, greet.__name__ would be “wrapper”.

Timing Decorator

Example
import time

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

@timer
def slow_sum(n):
    time.sleep(0.2)
    return sum(range(n))

print(slow_sum(1_000_000))
Output
slow_sum took 0.21s
499999500000

Explanation: Useful for finding slow steps in a data pipeline. The exact time varies by computer.

Decorator with Arguments

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

@repeat(3)
def hi():
    return "hi"

print(hi())
Output
['hi', 'hi', 'hi']

Explanation: To accept arguments, add one more outer function: repeat(3) returns the actual decorator.

Built-in: lru_cache

Example
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(80))
Output
23416728348467685

Explanation: Without caching, this recursive Fibonacci would take ages for n = 80. lru_cache remembers previous results (memoization), making it instant.

Common Decorators

Decorator Purpose
@property Method used like an attribute
@staticmethod / @classmethod Methods that do not need the instance
@lru_cache / @cache Memoize results
@dataclass Auto-generate __init__, __repr__ for data classes
@app.get(“/path”) Register a web route (FastAPI/Flask)
@tool Turn a function into an AI-agent tool (LangChain)

Series

Python series: What is Python · Installation · Syntax · Variables · Operators · Decisions · Loops · Strings · Lists · Dictionary · Functions · Lambda · Modules · Files · Exceptions · OOP · Classes & Objects · Inheritance · Decorators · Generators · Virtual Environments

Interview Questions

Q: What is a decorator?
A callable that takes a function and returns a new function with added behaviour.

Q: Why use functools.wraps?
To preserve the wrapped function’s name, docstring and metadata.

Practice Exercises

  1. Write a @log decorator that prints the function name and arguments.
  2. Write a @retry(n) decorator that retries a function n times if it raises an exception.

Summary

Decorators wrap functions to add behaviour cleanly. Use *args/**kwargs in the wrapper, @wraps to keep metadata, an extra layer for arguments, and built-ins like lru_cache.

Next: Generators

About Machine Learning

Check Also

Python Object-Oriented Programming (OOP): Encapsulation, Abstraction, Polymorphism

OOP in Python: encapsulation with private attributes and @property, abstraction, polymorphism and why OOP matters in data science.