Home > OS >  Get async object from module exactly once
Get async object from module exactly once

Time:01-21

I have module serv.py:

async def init_serv():
    serv = Serv()
    return await serv.init_with_params()

(of course, this is an abbreviated version)

In other modules I am doing:

from serv import init_serv

serv = init_serv()

This works fine, but whenever I import this module it creates a new instance of it.

I would like to have one instance, so if it wasn't asynchronous I could do that:

serv.py:

async def init_serv():
    serv = Serv()
    return await serv.init_with_params()

serv = init_serv()

and in other modules:

from serv import serv

But this obviously doesn't work because I'm calling an asynchronous function outside the async function.

What is the best solution for this?

CodePudding user response:

i think you are looking for a singleton pattern.(which is somehow an anti pattern but not in this situation)

Why is Singleton considered an anti-pattern?

What are drawbacks or disadvantages of singleton pattern?

class ClssNme:

    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(ClssNme, cls).__new__(cls)
        return cls.instance
  • Related