Skip to main content

Advanced Guide to Python Decorators | Expert Python Techniques

In Python, decorators are a powerful feature used to modify or enhance functions and classes. They are a key part of advanced metaprogramming and are frequently used in logging, authentication, caching, metrics, and tracing in production systems. This document provides an in-depth explanation of the syntax and all common use cases of Python decorators with professional examples aimed at deep learning engineers.

1. Basic Syntax of a Decorator

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

@my_decorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("Alice")

@my_decorator is equivalent to writing say_hello = my_decorator(say_hello).

2. Stacking Multiple Decorators

def deco1(func):
    def wrapper(*args, **kwargs):
        print("deco1")
        return func(*args, **kwargs)
    return wrapper

def deco2(func):
    def wrapper(*args, **kwargs):
        print("deco2")
        return func(*args, **kwargs)
    return wrapper

@deco1
@deco2
def greet():
    print("Greetings")

greet()

This applies decorators from the bottom up: greet = deco1(deco2(greet)).

3. Parameterized Decorators

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

@repeat(3)
def shout():
    print("Python!")

shout()

This is called a decorator factory that generates decorators dynamically.

4. Using functools.wraps

from functools import wraps

def log(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log
def process():
    """Does something important"""
    print("Processing")

print(process.__name__)
print(process.__doc__)

@wraps preserves the metadata (name, docstring) of the original function.

5. Applying Decorators to Classes

def class_decorator(cls):
    cls.extra_attr = 'injected'
    return cls

@class_decorator
class MyClass:
    pass

print(MyClass.extra_attr)

Since classes are objects, decorators can wrap them too.

6. Decorating Methods Inside a Class

def log_method(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        print(f"Method {func.__name__} called")
        return func(self, *args, **kwargs)
    return wrapper

class Logger:
    @log_method
    def run(self):
        print("Running")

Logger().run()

7. Using Decorators for Authentication

def require_admin(func):
    @wraps(func)
    def wrapper(user):
        if user != 'admin':
            raise PermissionError("Access denied")
        return func(user)
    return wrapper

@require_admin
def view_dashboard(user):
    print("Dashboard visible")

view_dashboard("admin")

8. Advanced Use: Class-Based Decorators

class CountCalls:
    def __init__(self, func):
        self.func = func
        self.calls = 0

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

@CountCalls
def hello():
    print("Hello")

hello()
hello()

Conclusion

Decorators are a vital tool for advanced Python developers. They increase code modularity, reusability, and readability. The provided examples demonstrate how decorators can be applied in real-world machine learning and deep learning projects, especially for logging, validation, caching, and profiling. functools.wraps is particularly essential to maintain proper function introspection.

References

Comments

Popular

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...

RF-DETR: Overcoming the Limitations of DETR in Object Detection

RF-DETR (Region-Focused DETR), proposed in April 2025, is an advanced object detection architecture designed to overcome fundamental drawbacks of the original DETR (DEtection TRansformer) . In this technical article, we explore RF-DETR's contributions, architecture, and how it compares with both DETR and the improved model D-FINE . We also provide experimental benchmarks and discuss its real-world applicability. RF-DETR Architecture diagram for object detection Limitations of DETR DETR revolutionized object detection by leveraging the Transformer architecture, enabling end-to-end learning without anchor boxes or NMS (Non-Maximum Suppression). However, DETR has notable limitations: Slow convergence, requiring heavy data augmentation and long training schedules Degraded performance on low-resolution objects and complex scenes Lack of locality due to global self-attention mechanisms Key Innovations in RF-DETR RF-DETR intr...