Skip to content Skip to sidebar Skip to footer

Asyncio.run Fails When Loop.run_until_complete Works

This code fails: import asyncio from motor import motor_asyncio _client = motor_asyncio.AsyncIOMotorClient() _db = _client.db users = _db.users async def main(): await use

Solution 1:

What the matter? I thought asyncio.run is a shortcut for this two lines.

No, it does much more. In particular it creates and sets an new event loop. And this is why you get error: AsyncIOMotorClient() creates some async stuff for default event loop, but another loop created by asyncio.run tries to use it.

If you want to preserve asyncio.run you should move init stuff inside main():

# ...

_client = None
_db = None
users = Noneasyncdefmain():
    global _client, _db, users
    _client = motor_asyncio.AsyncIOMotorClient()
    _db = _client.db
    users = _db.users

    # ...

It's a good idea in general to start things when event loop is already set and running instead of doing something at module-level.

Post a Comment for "Asyncio.run Fails When Loop.run_until_complete Works"