Understanding the Error
When programming with Python, a ValueError
suggesting an expected coroutine but received a function typically occurs within an asynchronous context. This error indicates that an asynchronous function (defined using async def
) is expected where a coroutine object is required, but a regular function was provided instead. It generally happens when you invoke an asynchronous function without the await
keyword. The await
keyword is essential in telling Python to wait for the completion of the asynchronous operation.
Addressing the Error
To fix this error, first, ensure that the function intended to be executed asynchronously is defined using async def
instead of the regular def
. Then, when calling this asynchronous function, use the await
keyword before the function call. This allows the event loop to manage the asynchronous call appropriately.
Working Example
The following code illustrates the correct implementation of an asynchronous function and its invocation:
import asyncio
async def do_something():
print('Doing something asynchronously')
await asyncio.sleep(1) # Simulate an I/O operation
async def main():
await do_something()
if __name__ == '__main__':
asyncio.run(main())
Alternative Solutions
If the function in question is not designed to be asynchronous but is required in an async context, one of the solutions is to run it in a separate executor using loop.run_in_executor
. Another option is refactoring the synchronous function as an asynchronous one if possible.