[Python] How to set class attribute with await in __init__

Discussão em 'Python' iniciado por Stack, Maio 4, 2025.

  1. Stack

    Stack Membro Participativo

    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()

    Continue reading...

Compartilhe esta Página