0

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?

saydiva
  • 17
  • 4

1 Answers1

0

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
Amin S
  • 546
  • 1
  • 14