How to set class attribute with await in __init__

后端 未结 5 2044
醉话见心
醉话见心 2020-11-28 19:04

How can I define a class with await in the constructor or class body?

For example what I want:

im         


        
5条回答
  •  执笔经年
    2020-11-28 19:53

    Better yet you can do something like this, which is very easy:

    import asyncio
    
    class Foo:
        def __init__(self, settings):
            self.settings = settings
    
        async def async_init(self):
            await create_pool(dsn)
    
        def __await__(self):
            return self.async_init().__await__()
    
    loop = asyncio.get_event_loop()
    foo = loop.run_until_complete(Foo(settings))
    

    Basically what happens here is __init__() gets called first as usual. Then __await__() gets called which then awaits async_init().

提交回复
热议问题