The double_args Decorator in Python 2026 – Practical Example
The double_args decorator is a classic teaching example that demonstrates how to create a decorator that modifies the arguments passed to a function before calling it. In this case, it doubles every numeric argument passed to the decorated function.
TL;DR — What double_args Does
- Takes a function and returns a new function (wrapper)
- Doubles every integer or float argument before calling the original function
- Leaves non-numeric arguments unchanged
- Preserves the original function’s name and docstring using
@wraps
1. Complete Implementation
from functools import wraps
from typing import Callable, Any
def double_args(func: Callable) -> Callable:
"""Decorator that doubles all numeric arguments passed to the function."""
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
# Double every numeric argument
new_args = []
for arg in args:
if isinstance(arg, (int, float)):
new_args.append(arg * 2)
else:
new_args.append(arg)
# Call the original function with modified arguments
return func(*new_args, **kwargs)
return wrapper
2. Usage Examples
@double_args
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
@double_args
def greet(name: str, age: int) -> str:
return f"Hello {name}, you are {age} years old."
print(add(5, 10)) # 30 (5*2 + 10*2)
print(greet("Alice", 25)) # Hello Alice, you are 50 years old.
3. Best Practices When Writing Similar Decorators
- Always use
@wraps(func)to preserve metadata - Handle both
*argsand**kwargsproperly - Be careful with type checking inside the wrapper
- Document clearly what the decorator modifies
- Keep the wrapper logic as simple and fast as possible
Conclusion
The double_args decorator is an excellent example for understanding how decorators can inspect and modify function arguments. In 2026, this pattern is commonly used as a teaching tool and as a foundation for building more complex decorators like validation, logging, or transformation decorators.
Next steps:
- Try modifying the
double_argsdecorator to support different transformations (e.g.,square_args,uppercase_args) - Related articles: Decorators in Python 2026 • Writing Functions in Python 2026