Sub topic 12
Decorating async functions
This chapter assumes you can write a basic decorator with functools.wraps, forward *args and **kwargs, and that you have seen async def and await. You don't need to know asyncio internals.
Why async needs its own wrapper
Calling an async def function does not run its body. It returns a coroutine object, which runs only when something awaits it or an event loop schedules it. A decorator that returns a plain def wrapper therefore returns that coroutine unchanged. The wrapper can't see when the work starts or finishes.
To run code before and after the body, the wrapper must itself be async def and await the wrapped call.
import asyncio
import functools
def log_calls(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return await func(*args, **kwargs)
return wrapper
@log_calls
async def fetch(value):
await asyncio.sleep(0.01)
return value
print(asyncio.run(fetch(42)))fetch(42) now returns the coroutine of wrapper. When the event loop runs it, the wrapper prints, awaits the original fetch, and returns its result.
The common mistake: a sync wrapper around a coroutine
This timer looks fine and is wrong:
import asyncio
import functools
import time
def broken_timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs) # returns a coroutine, does not run it
finally:
print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
return wrapper
@broken_timer
async def pause():
await asyncio.sleep(0.1)
asyncio.run(pause())It prints a time near 0.0000s, because it only measured how long it took to create the coroutine. The sleep happens later, outside the try block. No error is raised, so the bug is easy to miss.
The fix is the same shape as log_calls: use async def wrapper and return await func(...) inside the try.
Supporting both sync and async functions
A reusable decorator often has to accept either kind. Use inspect.iscoroutinefunction to choose the wrapper at decoration time:
import asyncio
import functools
import inspect
import time
def timed(func):
if inspect.iscoroutinefunction(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return await func(*args, **kwargs)
finally:
print(f"{func.__name__} took {time.perf_counter() - start:.2f}s")
else:
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
print(f"{func.__name__} took {time.perf_counter() - start:.2f}s")
return wrapper
@timed
async def pause():
await asyncio.sleep(0.1)
@timed
def work():
return sum(range(1_000_000))
asyncio.run(pause()) # pause took 0.10s (approximately)
work()The check runs once, when the decorator is applied, not on every call. This keeps the sync path free of any event-loop requirement.
Points to remember
- Calling an async function creates a coroutine. The wrapper must
awaitit to get the result. - The wrapper needs
async defforawaitto be legal inside it. functools.wrapsstill applies and copies the name and docstring as usual.- Decorator factories work the same way. Only the innermost
wrapperbecomesasync def. - Blocking calls such as
time.sleepinside an async wrapper stall the whole event loop. Useawait asyncio.sleepfor delays.
Exercise
You write a retry decorator with a plain def wrapper that calls func(*args, **kwargs) inside try/except, and apply it to an async def function that sometimes raises. Why do the retries never trigger, and what two changes fix it?
Show answer
Calling the async function only creates a coroutine, and that doesn't raise. The exception happens later, when the coroutine is awaited, which is outside the wrapper's try/except. Make the wrapper async def and write return await func(*args, **kwargs) inside the try block, so exceptions raised while the body runs are caught and the retry loop can run again.