How can I define a class with await
in the constructor or class body?
For example what I want:
import asyncio
# some code
class Foo(object):
async def __init__(self, settings):
self.settings = settings
self.pool = await create_pool(dsn)
foo = Foo(settings)
# it raises:
# TypeError: __init__() should return None, not 'coroutine'
or example with class body attribute:
class Foo(object):
self.pool = await create_pool(dsn) # Sure it raises syntax Error
def __init__(self, settings):
self.settings = settings
foo = Foo(settings)
My solution (But I would like to see a more elegant way)
class Foo(object):
def __init__(self, settings):
self.settings = settings
async def init(self):
self.pool = await create_pool(dsn)
foo = Foo(settings)
await foo.init()
__new__
, although it might not be elegant β Bullfrog_pool_init(dsn)
and then calling it from__init__
? It would preserve the init-in-constructor appearance. β Benzoin@classmethod
π it's an alternate constructor. put the async work there; then in__init__
, just set theself
attributes β Rager