Unlock Python Power: Master Decorators for Cleaner, Reusable Code
This article explains Python decorators—how they wrap functions to add behavior without modifying the original code—provides clear syntax examples, a practical timing decorator, a class‑diagram illustration, and shows how the @tool decorator integrates functions into LangChain agents.
What Is a Decorator?
Imagine you have a function and want to add extra behavior such as logging, permission checks, or timing without changing its source code. A decorator is a special kind of function that receives another function as an argument and returns a new callable that wraps the original.
In Python, the @ symbol is syntactic sugar for applying a decorator.
@my_decorator
def say_hello():
print("Hello!")The above is equivalent to:
def say_hello():
print("Hello!")
say_hello = my_decorator(say_hello)The @my_decorator line tells Python to pass say_hello to my_decorator and assign the returned wrapper back to say_hello.
A Simple Example
Below is a basic decorator that measures and prints a function’s execution time.
import time
def timer_decorator(func):
"""A simple timing decorator"""
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs) # call original function
end_time = time.time()
print(f"Function '{func.__name__}' took {end_time - start_time:.4f} seconds")
return result
return wrapper
@timer_decorator
def slow_function(delay):
"""A simulated time‑consuming function"""
print(f"Starting slow_function, will pause {delay} seconds...")
time.sleep(delay)
print("slow_function finished.")
return "Operation complete"
# Call the decorated function
message = slow_function(2)
print(f"Function return value: {message}")Running the script prints the execution time of slow_function even though the function itself contains no timing code—the decorator adds that capability transparently.
Decorator Design Pattern Class Diagram
The diagram below visualizes how a decorator wraps a component to extend its functionality.
Understanding the @tool Decorator in LangChain
In the file c:\src\google\A2A\samples\python\agents\langgraph\agent.py, the @tool decorator is used as follows:
from langchain_core.tools import tool
# ...code...
@tool
def get_exchange_rate(
currency_from: str = "USD",
currency_to: str = "EUR",
currency_date: str = "latest",
):
"""Use this to get current exchange rate.
# ... (function docstring) ...
"""
# ... (function implementation) ...The @tool decorator, provided by the langchain_core.tools library, performs three main actions:
Register the tool : It registers get_exchange_rate as a tool so that LangChain or LangGraph can discover and invoke it.
Extract metadata : It reads the function name, docstring (used as the tool description), and parameters (including type hints and default values) to inform the AI model how to call the tool.
Standardize the interface : It may wrap the function into an object that conforms to LangChain’s tool specification, allowing agents such as create_react_agent to call it uniformly.
In simple terms, the @tool decorator tags get_exchange_rate as a usable tool for LangChain agents, enabling models like ChatGoogleGenerativeAI to automatically invoke it when exchange‑rate information is needed. Without the decorator, the function remains a regular Python function that LangChain cannot automatically discover.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
