Sub topic 6
Forwarding arguments in wrappers and decorators
This chapter assumes you can define and call functions with default values, and that you know what *args and **kwargs collect and how * and ** unpack values at a call site. It also assumes you know that functions are objects you can pass around and return. Here those pieces combine into the most common real-world use of both syntaxes: a function that wraps another function without knowing its signature.
The forwarding problem
Suppose you want to add logging, timing, or caching to many functions. Each one has a different signature: add(a, b=0), connect(host, *, timeout=5), render(template, **context). A wrapper that adds the behavior must accept whatever call the original accepts, and then make that same call.
You cannot write that wrapper with named parameters, because it would have to list every parameter of every function it wraps. The solution is to accept everything and pass everything on:
def wrapper(*args, **kwargs):
...
return func(*args, **kwargs)In the signature, *args packs all positional arguments into a tuple and **kwargs packs all keyword arguments into a dictionary. In the call, *args and **kwargs unpack them again. The wrapper never inspects them. Each value arrives at func in the same position or under the same name it had when the caller supplied it.
A first forwarding decorator
A decorator is a function that takes a function and returns a replacement. The @name line above a def is shorthand for reassigning the name:
@log_calls
def add(a, b=0):
return a + b
# is equivalent to:
# add = log_calls(add)Here is a decorator that measures how long a call takes:
import functools
import time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.3f}s")
return wrapper
@timed
def slow_add(a, b=0):
time.sleep(0.1)
return a + b
print(slow_add(1, b=2))
# slow_add took 0.100s (the exact time varies)
# 3Three details matter here.
- The return value is forwarded.
return func(*args, **kwargs)hands the result back to the caller. If you writefunc(*args, **kwargs)on its own line and forgetreturn, every decorated function silently returnsNone. try/finallyruns the timing code even whenfuncraises. The exception still propagates to the caller. This is the right default for a wrapper: it should not swallow errors it does not own.- Both
*argsand `kwargsare forwarded.** Dropping**kwargs` from either the signature or the call is a common mistake. It breaks only the calls that use keyword arguments, so tests that use only positional calls may not catch it.
Because the wrapper never names the parameters, slow_add(1, 2), slow_add(1, b=2) and slow_add(a=1, b=2) all work. The tuple and dictionary the wrapper builds record exactly how each call was written.
What `functools.wraps` does
Decorating replaces the original function with wrapper. Without extra work, the replacement reports its own identity. Compare the two decorators below:
import functools
import inspect
def without_wraps(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def with_wraps(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@without_wraps
def a(x, y=1):
"""Doc for a."""
return x + y
@with_wraps
def b(x, y=1):
"""Doc for b."""
return x + y
print(a.__name__, a.__doc__) # wrapper None
print(b.__name__, b.__doc__) # b Doc for b.
print(inspect.signature(a)) # (*args, **kwargs)
print(inspect.signature(b)) # (x, y=1)
print(b.__wrapped__ is not None) # Truefunctools.wraps(func) copies __name__, __qualname__, __doc__, __module__ and the annotations from func onto the wrapper, and merges func.__dict__ into the wrapper's. It also sets wrapper.__wrapped__ = func. The inspect.signature function follows __wrapped__, so tools that read signatures (help systems, IDEs, documentation generators, frameworks that inspect parameters) see the original parameters instead of (*args, **kwargs).
wraps does not change how the wrapper behaves. If you call b(1, 2, 3), the wrapper accepts it and func raises the TypeError. The error message names the original function, and the traceback also shows the wrapper frame.
Decorators that take arguments
Sometimes you want to configure a decorator: @retry(times=3). This needs one more level of nesting. The outer function takes the configuration and returns the actual decorator. The decorator takes the function and returns the wrapper.
import functools
def retry(times=3, exceptions=(Exception,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
last_error = None
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except exceptions as error:
last_error = error
print(f"attempt {attempt} failed: {error}")
raise last_error
return wrapper
return decorator
calls = {"count": 0}
@retry(times=3, exceptions=(ValueError,))
def flaky(value, *, scale=1):
calls["count"] += 1
if calls["count"] < 3:
raise ValueError(f"not ready ({calls['count']})")
return value * scale
print(flaky(7, scale=2))
# attempt 1 failed: not ready (1)
# attempt 2 failed: not ready (2)
# 14@retry(times=3, ...) is evaluated first and returns decorator. Python then applies decorator to flaky. Only the innermost function uses *args and **kwargs. The outer layers have fixed, named parameters because you control them.
Note that flaky has a keyword-only parameter scale. The wrapper forwards scale=2 as a keyword, so the original signature's rules still apply.
Wrappers that consume some arguments
A wrapper does not have to forward everything. It can take a few parameters of its own and pass the rest on. Put the wrapper's own parameters after *args, which makes them keyword-only:
import functools
def quietable(func):
@functools.wraps(func)
def wrapper(*args, verbose=False, **kwargs):
if verbose:
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@quietable
def shout(text, times=1):
return (text.upper() + "! ") * times
print(shout("hi", times=2)) # HI! HI!
print(shout("hi", times=2, verbose=True))
# calling shout
# HI! HI! The verbose argument is captured by the wrapper and never reaches shout. This is useful, but it has two costs:
- If the wrapped function has its own
verboseparameter, the wrapper intercepts it and the function never sees it. inspect.signature(shout)follows__wrapped__and reports(text, times=1). It does not showverbose, so the added option is invisible to help tools. Document it in the decorator's docstring.
Use unusual names for wrapper-only options, or make the wrapper configurable through the decorator factory instead (@quietable(verbose=True)).
Decorating methods
You rarely need special code for methods. When Python calls a method, it puts the instance first in the positional arguments, so self lands in args[0] and is forwarded like any other value:
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__} with {len(args)} positional and {len(kwargs)} keyword")
return func(*args, **kwargs)
return wrapper
class Counter:
def __init__(self):
self.value = 0
@log_calls
def bump(self, step=1):
self.value += step
return self.value
c = Counter()
print(c.bump(step=5))
# calling bump with 1 positional and 1 keyword
# 5The wrapper counts one positional argument, which is self. This works because a plain function stored on a class becomes a bound method when accessed through an instance, and the wrapper is a plain function. Wrappers built as classes with __call__ need extra work (they must implement __get__), which is why function-based decorators are the usual choice.
Forwarding in inheritance
Wrappers are not the only place where forwarding pays off. A subclass often adds one option and leaves the rest to its parent class:
class Base:
def __init__(self, name, *, debug=False):
self.name = name
self.debug = debug
class Child(Base):
def __init__(self, *args, retries=3, **kwargs):
super().__init__(*args, **kwargs)
self.retries = retries
c = Child("job", debug=True, retries=5)
print(c.name, c.debug, c.retries) # job True 5Child consumes retries and forwards everything else. If Base later gains a new parameter, Child supports it without edits. The cost is the same as for wrappers: Child's own signature no longer documents what it accepts, so list the forwarded parameters in the docstring or write them out explicitly when the set is small and stable.
Wrapping async functions
A wrapper around an async def function must itself be async def and must await the call. A plain wrapper would return the coroutine without running it, so any timing or error handling would apply to creating the coroutine and not to running it.
import asyncio
import functools
def logged(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
print(f"start {func.__name__}")
result = await func(*args, **kwargs)
print(f"end {func.__name__}")
return result
return wrapper
@logged
async def fetch(n, *, delay=0):
await asyncio.sleep(delay)
return n * 2
print(asyncio.run(fetch(4, delay=0.01)))
# start fetch
# end fetch
# 8The forwarding itself is unchanged: *args and **kwargs collect, then unpack.
Common mistakes in forwarding code
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `func(*args, **kwargs)` without `return` | Decorated function returns `None` | `return func(*args, **kwargs)` |
| Forwarding only `*args` | `TypeError: unexpected keyword argument` on keyword calls | Add `**kwargs` to both signature and call |
| Writing `func(args, kwargs)` | Original receives one tuple and one dict as two arguments | Add the `*` and `**` at the call |
| Omitting `functools.wraps` | Wrong `__name__`, lost docstring, signature shows `(*args, **kwargs)` | Add `@functools.wraps(func)` to the wrapper |
| Returning `wrapper()` instead of `wrapper` | Decoration runs the wrapper immediately and fails or returns a result | Return the function object, with no parentheses |
| Using `@factory` instead of `@factory()` | Decorated name becomes a function that returns a function | Call the factory |
| Plain wrapper around `async def` | Timing or error handling misses the real work | Make the wrapper `async def` and `await` |
| Wrapper option clashes with a wrapped parameter | The wrapped function never receives that argument | Use a distinctive name or configure the decorator instead |
Another gotcha is mutating args or kwargs in a wrapper. args is a tuple, so you cannot modify it in place. kwargs is a fresh dictionary for each call, so modifying it is safe and does not change the caller's dictionary, even if the caller used **options. Python builds a new dictionary when it packs keyword arguments. To change a positional value, build a new tuple, for example args = (args[0] * 2, *args[1:]), and make sure it has at least one element first.
Summary of the pattern
Every forwarding wrapper has the same shape:
- Accept
*args, **kwargs(plus any keyword-only options of its own). - Do any work before the call.
- Call
func(*args, **kwargs)and keep the result, orreturnit directly. - Do any work after the call.
- Return the result.
Apply @functools.wraps(func) to the wrapper, and add an outer function when the decorator needs configuration.
Exercise
Write a decorator count_calls that counts how many times the decorated function has been called and stores the count in an attribute wrapper.calls (starting at 0). It must work for functions with any signature, return the original result, and keep the original __name__. Show that it works on def add(a, b=0) after calling add(1) and add(2, b=3).
Show answer
import functools def countcalls(func): @functools.wraps(func) def wrapper(args, kwargs): wrapper.calls += 1 return func(args, **kwargs) wrapper.calls = 0 return wrapper @countcalls def add(a, b=0): return a + b print(add(1)) # 1 print(add(2, b=3)) # 5 print(add.calls) # 2 print(add._name_) # add
Exercise
A decorator is written as follows, and greet("Ada", punctuation="!") raises TypeError: wrapper() got an unexpected keyword argument 'punctuation'. What is wrong, and how do you fix it?
def shout(func):
def wrapper(args):
return func(args).upper()
return wrapper
@shout
def greet(name, punctuation="."):
return f"hello {name}{punctuation}"
Show answer
The wrapper accepts only positional arguments, so any keyword argument is rejected before func is called. Add **kwargs to the signature and forward it: def wrapper(*args, **kwargs): return func(*args, **kwargs).upper(). Adding @functools.wraps(func) is also advisable so greet keeps its name and signature.
Exercise
You write @retry (without parentheses) above a function, where retry(times=3) is a decorator factory that returns decorator. What does the name of the decorated function refer to afterwards, and why is the mistake easy to miss?
Show answer
The name refers to the inner decorator function, because retry(func) binds func to times and returns decorator. No error is raised at decoration time. The mistake shows up only when you call the function and get a wrapper back instead of a result.