Tech With Galvan
Back to Articles
TechSep 13, 2026 • 5 min read

Python Decorators: Deep Dive (Beyond @property)

Python decorators explained — functions as objects, @wraps, decorator factories, class decorators, and functools.lru_cache, with real examples.

Galvan
Galvan

Founder & Creator

Introduction

You’ve seen @property, @staticmethod, @app.route. Decorators are everywhere in Python — but most developers use them without understanding how they work. This post goes deep: from the basics to decorator factories, class decorators, and the patterns you’ll actually use.

The foundation: functions are objects

In Python, functions are first-class objects — you can pass them around, store them, and return them:

def greet(name):
    return f"Hello, {name}"

# Functions are objects
say_hi = greet
print(say_hi("Galvan"))   # Hello, Galvan

# Functions can be arguments
def call_twice(func, arg):
    return func(func(arg))

def upper(s):
    return s.upper()

print(call_twice(upper, "hi"))   # HI

A decorator is just a function that takes a function and returns a (usually enhanced) function.

Your first decorator

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("galvan"))   # HELLO, GALVAN

@shout is syntactic sugar for greet = shout(greet). The decorator replaces greet with wrapper.

*args, **kwargs — the universal wrapper

Always use *args, **kwargs in wrappers so the decorator works with any function signature:

def log_call(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args}, {kwargs}")
        result = func(*args, **kwargs)
        print(f"Returned {result}")
        return result
    return wrapper

functools.wraps — preserve metadata

Without @wraps, the wrapper hides the original function’s name and docstring:

from functools import wraps

def log_call(func):
    @wraps(func)   # copies __name__, __doc__, __wrapped__, etc.
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_call
def add(a, b):
    """Add two numbers."""
    return a + b

print(add.__name__)   # "add" (not "wrapper")
print(add.__doc__)    # "Add two numbers."

Always use @wraps. Without it, debugging, help(), and introspection break.

Decorator factories (decorators with arguments)

To pass arguments to a decorator, wrap it in another function:

def repeat(n):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(n):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def say_hi():
    print("hi")

say_hi()   # hi hi hi

@repeat(3) calls repeat(3) which returns decorator, which then wraps say_hi. Three levels of nesting — the most common decorator pattern.

Class decorators

Decorators can be classes (useful for stateful decorators):

class CountCalls:
    def __init__(self, func):
        self.func = func
        self.count = 0
        wraps(func)(self)   # preserve metadata

    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"Call #{self.count}")
        return self.func(*args, **kwargs)

@CountCalls
def greet(name):
    return f"Hello, {name}"

greet("Galvan")   # Call #1
greet("World")    # Call #2
print(greet.count)  # 2

Common real-world decorators

1. Timing

import time
from functools import wraps

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

@timer
def slow_function():
    time.sleep(1)

2. Retry

import time
from functools import wraps

def retry(max_attempts=3, delay=1.0):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, max_attempts + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts:
                        raise
                    time.sleep(delay)
        return wrapper
    return decorator

@retry(max_attempts=3, delay=0.5)
def fetch_data():
    ...

3. Caching (lru_cache)

from functools import lru_cache

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

fibonacci(100)   # instant (cached)

lru_cache is the most useful built-in decorator — memoizes function results by arguments.

4. Validation

def validate_positive(func):
    @wraps(func)
    def wrapper(x, *args, **kwargs):
        if x <= 0:
            raise ValueError("x must be positive")
        return func(x, *args, **kwargs)
    return wrapper

@validate_positive
def sqrt(x):
    return x ** 0.5

Stacking decorators

Decorators apply bottom-up:

@decorator_a
@decorator_b
def func():
    ...

# Equivalent to: func = decorator_a(decorator_b(func))

Order matters. @timer above @retry times the retries; @retry above @timer retries only the final failure.

Common mistakes

  • Forgetting @wraps — breaks help(), __name__, and introspection.
  • Mutable default args in wrappers — def wrapper(items=[]) shares state. Use None and initialize inside.
  • Decorating methods without self — def wrapper(func) on a method breaks. Use *args, **kwargs and access args[0] if needed (or use descriptors).
  • Over-decorating — 5+ decorators on one function is unreadable. Refactor instead.
  • Side effects in decorators — decorators should be transparent; surprising side effects (like global state changes) make code hard to debug.

Key Concepts

  • Decorator = function that takes a function and returns a function
  • @wraps = preserves original metadata
  • Decorator factory = decorator that takes arguments (three levels of nesting)
  • lru_cache = built-in memoization
  • Stacking = apply bottom-up

What to Try Next

FAQ

Decorators vs context managers (with)?

Decorators wrap functions (compile-time). Context managers wrap blocks (runtime). Use decorators for cross-cutting concerns (logging, caching, auth); context managers for resource management (files, locks, DB connections).

Can I decorate a class?

Yes — class decorators receive the class and return a (possibly modified) class. Common use: registering classes in a registry, adding methods, or validating class attributes.

@property is a decorator — how does it work?

@property is a built-in descriptor that turns a method into a read-only attribute. It uses the descriptor protocol (__get__, __set__) under the hood. See the Python docs on descriptors for the deep dive.