Python Decorators: Unlocking the Magic of Code Reusability

Deepesh AgrawalDeepesh Agrawal
3 min read

Have you ever wished you could add superpowers to your functions—without changing their core logic? Imagine you’re a chef, and you want to sprinkle some extra flavor onto your dishes without rewriting the entire recipe. In Python, decorators are your secret spice!

What is a Decorator?

A decorator in Python is like a wrapper that adds new behavior to a function or class, without modifying its source code. This is incredibly useful for logging, access control, timing, and more.

The Classic Example: Timing a Function

Let’s say you want to measure how long a function takes to run. You could sprinkle timing code everywhere, but that gets messy fast. Enter decorators!

import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds")
        return result
    return wrapper

@timer_decorator
def slow_function():
    time.sleep(2)
    print("Function complete!")

slow_function()

Output

Function complete!
Function 'slow_function' executed in 2.0001 seconds

Why Decorators Matter

  • Code Reusability: Write once, use everywhere.

  • Separation of Concerns: Keep your core logic clean.

  • Readability: Instantly see what extra behaviors a function has, just by looking at the @decorator line.

Real-World Use Case: Authentication

Imagine you’re building a web app. You want to restrict access to certain functions unless the user is logged in. Decorators make this a breeze:

 def require_login(func):
    def wrapper(user, *args, **kwargs):
        if not user.is_authenticated:
            raise PermissionError("User must be logged in!")
        return func(user, *args, **kwargs)
    return wrapper

@require_login
def view_profile(user):
    print(f"Welcome, {user.name}!")

conclusion

Decorators are Python’s way of letting you add magic to your code—cleanly, elegantly, and powerfully. Next time you want to enhance a function, reach for a decorator and sprinkle some Pythonic brilliance!

A standout use case for Python decorators, now widely adopted in AI agent libraries for observability, is tracing and monitoring the execution of agent actions—similar to how platforms like AgentOps and Langfuse enable "spans" and "traces" for AI workflows.

Example: Tracing AI Agent Actions with a Decorator

In modern AI agent systems, every significant function or "step" the agent performs is wrapped with a decorator that automatically logs, traces, and times the operation. This provides a granular, real-time view of the agent's decision process, cost, latency, and errors—essential for debugging, optimization, and transparency.

import time

def trace_step(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        print(f"[TRACE] Starting '{func.__name__}'")
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"[TRACE] Finished '{func.__name__}' in {end_time - start_time:.2f}s")
        return result
    return wrapper

@trace_step
def fetch_user_profile(user_id):
    # Simulate agent logic
    time.sleep(0.5)
    return {"user_id": user_id, "profile": "data"}

@trace_step
def recommend_products(profile):
    # Simulate agent logic
    time.sleep(0.3)
    return ["product1", "product2"]

# Simulate agent workflow
profile = fetch_user_profile("user123")
recommendations = recommend_products(profile)

Why This Matters

  • Observability: Each agent action is traced, making it easy to debug and optimize workflows.

  • Performance Monitoring: Automatically captures execution time and can be extended to log errors, inputs, outputs, and costs.

  • Production-Readiness: This pattern underpins the monitoring features in libraries like AgentOps and Langfuse, which visualize traces, costs, and user interactions for AI agents in production.

10
Subscribe to my newsletter

Read articles from Deepesh Agrawal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Deepesh Agrawal
Deepesh Agrawal

building shits