Sub topic 12
Decorating async functions
This chapter assumes you can write a decorator with functools.wraps and *args/**kwargs, and that you know the basics of async def, await, and asyncio.run. It builds on the basic decorator pattern and shows what changes when the wrapped function is a coroutine function.
What goes wrong with a plain wrapper
Calling an async def function does not run its body. It returns a coroutine object, and the body runs only when something awaits that object. A decorator built for ordinary functions therefore sees the call return immediately.
The timer below is the usual synchronous version, applied to an async function.
import asyncio
import functools
import time
def sync_timer(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:.4f}s")
return wrapper
@sync_timer
async def pause():
await asyncio.sleep(0.2)
return "done"
async def main():
print(await pause())
asyncio.run(main())The output is roughly:
pause took 0.0000s
doneThe timer measured only the creation of the coroutine object, not the 0.2 seconds of sleeping. The same problem affects try/except blocks, since the exception is raised later, when the coroutine is awaited, long after the wrapper has returned.
The fix: an async wrapper that awaits
If the decorated function is a coroutine function, the wrapper must also be async def, and it must await the call. The wrapper then returns a coroutine of its own. The caller awaits that, and the wrapper awaits the original.
import asyncio
import functools
import time
def async_timer(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return await func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return wrapper
@async_timer
async def pause():
await asyncio.sleep(0.2)
return "done"
async def main():
print(await pause())
asyncio.run(main())This prints pause took 0.2...s followed by done. The structure matches the synchronous decorator. The only differences are async def on the wrapper and await on the call.
Checking what you built
inspect.iscoroutinefunction tells you whether a callable is a coroutine function. With an async wrapper, the decorated name still reports True, so frameworks that inspect handlers (web frameworks do this to decide whether to await a route) keep working. With a synchronous wrapper around an async function, it reports False.
import asyncio
import functools
import inspect
def sync_passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def async_passthrough(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
return await func(*args, **kwargs)
return wrapper
async def job():
return 1
print(inspect.iscoroutinefunction(sync_passthrough(job))) # False
print(inspect.iscoroutinefunction(async_passthrough(job))) # Truefunctools.wraps still matters here. It copies __name__, __doc__, and __wrapped__ exactly as it does for synchronous functions.
Decorator factories for async code
A decorator factory adds one more level of nesting, and the innermost wrapper is the async one. A retry decorator is a typical example.
import asyncio
import functools
def retry(times, delay=0.1, exceptions=(Exception,)):
def decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return await func(*args, **kwargs)
except exceptions as exc:
if attempt == times:
raise
print(f"attempt {attempt} failed: {exc!r}, retrying")
await asyncio.sleep(delay)
return wrapper
return decorator
calls = {"count": 0}
@retry(times=3, delay=0.05, exceptions=(ConnectionError,))
async def flaky():
calls["count"] += 1
if calls["count"] < 3:
raise ConnectionError("network down")
return "connected"
print(asyncio.run(flaky()))The output is:
attempt 1 failed: ConnectionError('network down'), retrying
attempt 2 failed: ConnectionError('network down'), retrying
connectedTwo details are worth noting:
- The wait between attempts uses
await asyncio.sleep(delay). Callingtime.sleep(delay)would freeze the whole event loop, so every other task would stall during the wait. - The
exceptionsparameter limits what is retried. Catching bareExceptionretries programming errors such asTypeError, which hides bugs.
Supporting both sync and async functions
Sometimes one decorator should work on any function. Decide once, at decoration time, which kind of wrapper to build.
import asyncio
import functools
import inspect
def log_calls(func):
if inspect.iscoroutinefunction(func):
@functools.wraps(func)
async def async_wrapper(*args, **kwargs):
print(f"calling {func.__name__} (async)")
return await func(*args, **kwargs)
return async_wrapper
@functools.wraps(func)
def sync_wrapper(*args, **kwargs):
print(f"calling {func.__name__} (sync)")
return func(*args, **kwargs)
return sync_wrapper
@log_calls
def add(a, b):
return a + b
@log_calls
async def fetch(value):
await asyncio.sleep(0.01)
return value
print(add(1, 2))
print(asyncio.run(fetch(7)))The check runs once, when the decorator is applied, not on every call. That keeps the per-call cost low and gives each wrapper the right type.
The cost is duplicated logic. If the shared part is more than a few lines, move it into a helper function that both wrappers call.
Wrapper types and what they do
| Decorated function | Wrapper | Result |
|---|---|---|
| `def` | `def` | Normal decorator. |
| `async def` | `async def` with `await` | Correct. Timing, `try`/`finally`, and retries work. |
| `async def` | `def` that returns `func(...)` | Runs, but cleanup code and exception handling run too early. `inspect.iscoroutinefunction` reports `False`. |
| `async def` | `async def` without `await` | Returns an un-awaited coroutine inside a coroutine. Callers get a coroutine object, not the result. |
| `def` | `async def` | Callers must now `await` a function that used to be synchronous. This breaks existing call sites. |
Common pitfalls
Forgetting `await`
If the wrapper contains return func(*args, **kwargs) inside async def, the caller awaits the wrapper and receives a coroutine object instead of a value. Python also warns RuntimeWarning: coroutine '...' was never awaited when the inner coroutine is discarded. The fix is return await func(...).
Blocking calls inside the wrapper
Anything slow inside an async wrapper blocks every task on the loop. Replace time.sleep with await asyncio.sleep. If you must call blocking code, such as a synchronous logging backend or file operations, run it with await asyncio.to_thread(...).
Swallowing cancellation
When a task is cancelled, asyncio.CancelledError is raised inside the awaited call. In Python 3.8 and later it inherits from BaseException, so except Exception does not catch it, which is the behavior you want. A bare except: or except BaseException: in a wrapper catches it and can make the task impossible to cancel. Use finally for cleanup and let cancellation propagate.
Decorating async generators
A function that contains both async def and yield is an async generator. Calling it returns an async iterator, and await func() fails on it. A wrapper for that case must itself be an async generator that iterates with async for item in func(*args, **kwargs): and yields each item. Writing one decorator that handles coroutine functions and async generators requires checking inspect.isasyncgenfunction as well.
Methods
Async methods need no special handling. self arrives as the first element of args, exactly as in the synchronous case, so async def wrapper(*args, **kwargs) works on methods unchanged.
Exercise
A teammate writes a @timer decorator with a regular def wrapper that does return func(*args, **kwargs) between two time.perf_counter() calls. They apply it to async def download(), which sleeps for two seconds, and the timer prints 0.0001s. Why, and how do you fix it?
Show answer
Calling download() only creates a coroutine object and returns it right away, so the timer measures the creation of that object, not its execution. Make the wrapper async def and use return await func(*args, **kwargs) inside the timed region, with functools.wraps kept on the wrapper.
Exercise
Write an async decorator with_timeout(seconds) (a decorator factory) that raises asyncio.TimeoutError if the wrapped coroutine function takes longer than seconds. Name the three nested functions and the standard-library call you would use.
Show answer
Outer with_timeout(seconds) returns decorator(func), which returns async def wrapper(*args, **kwargs), decorated with functools.wraps(func). Inside the wrapper, run return await asyncio.wait_for(func(*args, **kwargs), timeout=seconds). asyncio.wait_for cancels the inner coroutine and raises TimeoutError when the time limit passes. On Python 3.11 and later, async with asyncio.timeout(seconds): around an await func(...) also works.
Exercise
Your @log_calls decorator must support both def and async def functions. Where do you perform the inspect.iscoroutinefunction check, and why there?
Show answer
At decoration time, inside log_calls(func) before building a wrapper. The check runs once per decorated function instead of once per call, and it lets you return an async def wrapper for coroutine functions and a plain def wrapper for everything else, so inspect.iscoroutinefunction stays correct on the decorated name.