Get async object from module exactly once

Question:

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?

Asked By: saydiva

||

Answers:

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
Answered By: Amin S
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.