Skip to main content

Advanced Python

Decorators

Complete lesson for Decorators using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Decorators

Section: Advanced Python. Wrap functions and methods with reusable behaviour — timing, logging, validation, caching — using Python decorators and @ syntax.

Functions are first-class objects

  • You can assign functions to names, pass them as arguments, and return them from other functions.
  • A decorator is a callable that takes a function and returns a callable — usually a wrapper that adds behaviour.
  • Real life: a gift wrapper around a box — same gift, extra packaging before and after you open it.
def greet(name):
    return f"Hello, {name}"

say = greet
print(say("Ada"))

Closures — remembering the original function

  • An inner function can capture variables from the enclosing scope (including the original function).
  • That captured function is what the wrapper calls after/before its extra work.
  • Without a closure, a decorator could not remember which function to invoke.
def loudly(func):
    def wrapper(text):
        result = func(text)
        return result.upper()
    return wrapper

def message(text):
    return text

message = loudly(message)
print(message("hello"))

The @ syntax

  • @loudly above def message means message = loudly(message) — applied at definition time.
  • Order matters when stacking: the decorator closest to def runs first when wrapping.
  • Decorators run at import/definition time, not at call time — side effects in the decorator body happen early.
def loudly(func):
    def wrapper(text):
        return func(text).upper()
    return wrapper

@loudly
def message(text):
    return text

print(message("hello"))

Preserving arguments with *args and **kwargs

  • Real functions take varied signatures. Wrappers should accept *args, **kwargs and forward them.
  • Return the wrapped function’s return value unless you intentionally change the API.
  • Failing to forward kwargs is a common decorator bug.
def trace(func):
    def wrapper(*args, **kwargs):
        print("call", func.__name__, args, kwargs)
        return func(*args, **kwargs)
    return wrapper

@trace
def add(a, b, scale=1):
    return (a + b) * scale

print(add(2, 3, scale=10))

functools.wraps — keep metadata

  • A raw wrapper hides the original __name__, __doc__, and signature — painful for help() and debugging.
  • @functools.wraps(func) copies metadata onto the wrapper.
  • Always use wraps in production decorators.
import functools

def trace(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@trace
def area(width, height):
    """Return rectangle area."""
    return width * height

print(area.__name__)
print(area.__doc__)

Timing and logging decorators

  • Classic teaching examples: measure runtime, log calls, retry on failure, require login.
  • Keep wrappers thin — heavy logic belongs in helpers the wrapper calls.
  • Print timing after the call so failures still show elapsed time in a finally if you need it.
import functools
import time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            elapsed = time.perf_counter() - start
            print(f"{func.__name__} took {elapsed:.6f}s")
    return wrapper

@timed
def work():
    return sum(range(10000))

print(work())

Decorating methods

  • Instance methods still receive self as the first argument after decoration — forward *args correctly.
  • @classmethod and @staticmethod are built-in descriptors/decorators; stack carefully with custom ones.
  • Prefer decorating the function before @classmethod unless you know descriptor interaction rules.
import functools

def label(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        return f"[{self.tag}] {func(self, *args, **kwargs)}"
    return wrapper

class Box:
    def __init__(self, tag):
        self.tag = tag

    @label
    def describe(self, item):
        return item

print(Box("A").describe("book"))
L2

Advanced — Decorators

Parameterized decorators

  • To write @repeat(3), define an outer factory that takes arguments and returns the real decorator.
  • Pattern: decorate(func) inside repeat(n) inside three nested levels — factory → decorator → wrapper.
  • The @ form calls the factory immediately with the arguments, then applies the returned decorator to the function.
import functools

def repeat(times):
    def decorator(func):
        @functools.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 ping():
    print("pong")
    return "ok"

print(ping())

Decorator stacking order

  • `` @a @b def f(): ... ` means f = a(b(f)) — b wraps first, a` wraps the result.
  • On a call, the outermost wrapper (a) runs first on the way in.
  • Document order when mixing auth, caching, and timing — wrong order can cache unauthorized results.
def a(func):
    def wrapper():
        print("a-in")
        result = func()
        print("a-out")
        return result
    return wrapper

def b(func):
    def wrapper():
        print("b-in")
        result = func()
        print("b-out")
        return result
    return wrapper

@a
@b
def f():
    print("body")
    return 1

print(f())

Class-based decorators

  • A class with __call__ can act as a decorator: @Decorator constructs an instance around the function.
  • Useful when the decorator needs instance state (counters, configuration) without nested closures.
  • Parameterized class decorators implement __init__(self, ...) for args and __call__(self, func) for wrapping — or the reverse pattern with a nested wrap.
import functools

class CountCalls:
    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func
        self.count = 0

    def __call__(self, *args, **kwargs):
        self.count += 1
        print("calls", self.count)
        return self.func(*args, **kwargs)

@CountCalls
def inc(x):
    return x + 1

print(inc(1))
print(inc(2))

functools.lru_cache and cache decorators

  • @lru_cache(maxsize=128) memoises pure functions based on arguments — huge win for recursive algorithms.
  • Arguments must be hashable. Side-effecting functions should not be cached blindly.
  • cache_clear() resets; cache_info() shows hits/misses for tuning.
from functools import lru_cache

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

print(fib(30))
print(fib.cache_info())

Decorators that replace the function

  • A decorator may return a completely different callable (registration tables, plugin systems).
  • Flask/FastAPI-style @app.get registers a route and usually returns the original function for further stacking.
  • Always decide whether identity (wraps) or registry side effects matter more for your API.
L3

Tricky Interview Points

Q1) What is a decorator in Python?

Answer A callable that takes a function (or class) and returns a new callable, usually wrapping the original to add behaviour. The @syntax applies it at definition time.

Q2) What does @decorator mean?

Answer It is sugar for func = decorator(func), executed right after the function is defined.

Q3) Why use functools.wraps?

Answer It copies the original function metadata (__name__, __doc__, annotations, etc.) onto the wrapper so help(), debugging, and introspection still work.

Q4) How do you write a decorator that takes arguments?

Answer Write a factory: outer function takes decorator args and returns the actual decorator that takes the function and returns a wrapper.

Q5) In what order do stacked decorators apply?

Answer Bottom-up wrapping: @a above @b means f = a(b(f)). The top decorator is outermost at call time.

Q6) Can decorators wrap classes?

Answer Yes. A class decorator receives the class object and returns a class (or substitute). Common for registration and enriching classes.

Q7) What is a closure, and why do decorators need it?

Answer A nested function that remembers variables from its enclosing scope. Wrappers close over the original function to call it later.

Q8) What is lru_cache?

Answer A functools decorator that memoises function results keyed by arguments, with an optional max size and LRU eviction.

Q9) Do decorators run at import time or call time?

Answer The decorator function runs at definition/import time. The wrapper it returns runs on each call.

Q10) How do decorators interact with methods?

Answer Wrappers must forward self/cls correctly via *args/**kwargs. Be careful stacking with classmethod/staticmethod because of descriptor behaviour.

Q11) What is the difference between a decorator and a higher-order function?

Answer A decorator is a higher-order function (or callable) used specifically to wrap/replace another callable, often via @ syntax.

Q12) Can a decorator return something that is not a function?

Answer Yes, any callable (or even a non-callable if you never call it). Class decorators often return classes; some registries return the original unchanged.

L4

Simple Programs

Retry decorator

import functools

def retry(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last = None
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ValueError as exc:
                    last = exc
                    print(f"attempt {attempt} failed")
            raise last
        return wrapper
    return decorator

@retry(3)
def flaky(n):
    if n < 2:
        raise ValueError("too small")
    return n * 2

print(flaky(5))

Ensure non-negative arguments

import functools

def non_negative(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        for value in args:
            if isinstance(value, (int, float)) and value < 0:
                raise ValueError("negative not allowed")
        return func(*args, **kwargs)
    return wrapper

@non_negative
def distance(x, y):
    return abs(x - y)

print(distance(5, 2))

Simple memoisation without lru_cache

import functools

def memoize(func):
    cache = {}

    @functools.wraps(func)
    def wrapper(*args):
        if args not in cache:
            cache[args] = func(*args)
        return cache[args]

    wrapper.cache = cache
    return wrapper

@memoize
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(20))
print(len(fib.cache))

HTML tag decorator factory

import functools

def tag(name):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return f"<{name}>{func(*args, **kwargs)}</{name}>"
        return wrapper
    return decorator

@tag("strong")
def title(text):
    return text

print(title("Decorators"))

Register plugins with a decorator

REGISTRY = {}

def register(name):
    def decorator(func):
        REGISTRY[name] = func
        return func
    return decorator

@register("ping")
def ping():
    return "pong"

@register("echo")
def echo(x):
    return x

print(sorted(REGISTRY))
print(REGISTRY["ping"]())
print(REGISTRY["echo"]("hi"))
L5

Problem Solving Tricks

  • Always @functools.wraps(func) unless you intentionally replace the callable identity.
  • Forward with return func(*args, **kwargs) — forgetting return silently yields None.
  • Parameterized decorator? Three levels: factory → decorator → wrapper.
  • Stacking: closest decorator to def is applied first (f = outer(inner(f))).
  • lru_cache needs hashable args; convert lists to tuples before caching.
  • Keep decorator side effects idempotent — modules can be imported more than once in some tooling setups.
  • For methods, test with an instance; many bugs only show when self is present.
  • Use time.perf_counter() for timings, not time.time().
  • Prefer small composable decorators over one mega-wrapper.
  • In type-checked codebases, consider ParamSpec / Concatenate for typed wrappers (3.10+).
L6

Practice Programs List

  1. Write @logged that prints function name, args, kwargs, and return value.
  2. Build @repeat(n) and prove stacking order with print statements.
  3. Implement a class-based @CountCalls and assert .count after several calls.
  4. Decorate a recursive Fibonacci with lru_cache and compare call counts mentally with/without cache.
  5. Create @requires_ints that raises TypeError if any positional arg is not int.
  6. Register commands in a CLI dict using @command("name").
  7. Wrap an instance method that uses self and confirm wraps still shows the original name.
  8. Write a decorator that enforces a maximum runtime using time.perf_counter and raises TimeoutError (simulate with a short limit).