Advertisement
Advanced Python, Decorators

How do you write a decorator that works correctly on an async function (coroutine), given that a regular decorator's wrapper would break 'await' usage?

Short answer

The wrapper function itself must ALSO be declared 'async def' and use 'await' when calling the original coroutine — a plain synchronous wrapper calling an async function without awaiting it would just return an un-awaited coroutine object instead of the actual result.

Save Python mock interview
Advertisement
AModel answer
The wrapper function itself must ALSO be declared 'async def' and use 'await' when calling the original coroutine — a plain synchronous wrapper calling an async function without awaiting it would just return an un-awaited coroutine object instead of the actual result.
import functools

def async_logged(func):
    @functools.wraps(func)
    async def wrapper(*args, **kwargs):  # must ALSO be async
        print(f"Calling {func.__name__}")
        result = await func(*args, **kwargs)  # must await the coroutine
        return result
    return wrapper

@async_logged
async def fetch_data():
    await asyncio.sleep(1)
    return "data"
Real-world example
Adding logging or timing behavior consistently to async functions in an asyncio-based application.
Likely follow-ups
  • How would you write a SINGLE decorator that correctly handles BOTH sync and async functions automatically?
Related topics