Junior — Middle
How to implement a decorator in Python that can wrap asynchronous functions?
sobes.tech AI
Answer from AI
To create a decorator in Python that can wrap asynchronous functions, you need to define an asynchronous function inside the decorator and use await to call the original function. Here's an example of such a decorator:
import functools
def async_decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
print("Before calling the function")
result = await func(*args, **kwargs)
print("After calling the function")
return result
return wrapper
# Usage example
@async_decorator
async def async_func(x):
await asyncio.sleep(1)
return x * 2
# Call from an asynchronous context
import asyncio
async def main():
result = await async_func(10)
print(f"Result: {result}")
asyncio.run(main())
This decorator works correctly with asynchronous functions, allowing additional actions to be performed before and after the call to the original function.