Search code examples
pythonasynchronousasync-awaitbluetoothpython-asyncio

Asyncio | How to resolve "a coroutine was expected" error?


I grabed the two_devices.py code example from here: https://github.com/hbldh/bleak/blob/develop/examples/two_devices.py

When I try to execute it, I receive the following error:

Exception has occurred: ValueError
a coroutine was expected, got <_GatheringFuture pending>
  File "path to file", line 39, in <module>
    "F0CBEBD3-299B-4139-A9FC-44618C720157",
ValueError: a coroutine was expected, got <_GatheringFuture pending>

Can anyone provide some suggestions how to resolve this?


Solution

  • The linked code is incorrect. It's calling a synchronous function with asyncio.run, and it's never await-ing on asyncio.gather (and you can't use await in a synchronous function).

    A correct implementation would look something like this:

    ...
    
    async def main():
        return await asyncio.gather(*(connect_to_device(address)
                                      for address in addresses))
    
    if __name__ == '__main__':
        asyncio.run(
            main(
                [
                    "B9EA5233-37EF-4DD6-87A8-2A875E821C46",
                    "F0CBEBD3-299B-4139-A9FC-44618C720157",
                ]
            )
        )
    

    This is still problematic -- it will run, but the code never does anything with the return value from main.