Preserve Awaitable Behavior in Async Decorators
Core idea
An async decorator usually returns an async def wrapper that awaits the original callable and returns its result. functools.wraps preserves selected metadata, not execution behavior. Use try/finally for exit actions that must happen on failure or cancellation. A synchronous wrapper returning a coroutine can still be awaitable when called, but may not be recognized as a coroutine function.
import asyncio
async def main(): from functools import wraps from inspect import iscoroutinefunction def trace(fn): @wraps(fn) async def wrapper(*args, **kwargs): print('start') return await fn(*args, **kwargs) return wrapper @trace async def total(n, *, fee=1): return n+fee print(total.__name__, iscoroutinefunction(total)) print(await total(4,fee=2))
asyncio.run(main())The wrapper stays async, forwards keywords and returns the awaited value.
Expected output:
total Truestart6Run exit logic on failure
import asyncio
async def main(): from functools import wraps def traced(fn): @wraps(fn) async def wrapper(*args,**kwargs): try: return await fn(*args,**kwargs) finally: print('exit') return wrapper @traced async def fail(): raise ValueError('bad') try: await fail() except ValueError: print('caught')
asyncio.run(main())The finally block runs while the original exception propagates.
Expected output:
exitcaughtCommon mistake
Do not return fn(*args, **kwargs) from an async wrapper without awaiting it when the public contract promises the final value; this returns a nested coroutine instead. Do not silently suppress CancelledError.
Practice
Decorate an async function with a keyword-only argument. Verify its result, name, coroutine-function status and finally behavior during cancellation using an event.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async decorators
Check your understanding of async decorators.
What is printed?
import asyncio
async def main(): async def f(): return 3 async def wrapper(): return await f() print(await wrapper())
asyncio.run(main())What is printed?
import asyncio
async def main(): from inspect import iscoroutinefunction async def f(): return 1 print(iscoroutinefunction(f))
asyncio.run(main())What should an async wrapper return for a transparent result contract?
Does wraps alone make a synchronous wrapper async?