I have a Python 3 class that is currently a singleton defined using a @singleton
decorator, but occasionally it needs to not be a singleton.
Question: Is it possible to do something similar to passing a parameter when instantiating an object from the class and this parameter determines whether the class is a singleton or not a singleton?
I am trying to find an alternative to duplicating the class and making that not a singleton, but then we will have tons of duplicated code.
Foo.py
def singleton(cls):
instances={}
def getinstance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return getinstance
@singleton
Class Foo:
def hello(self):
print('hello world!')
FooNotSingleton.py
Class FooNotSingleton:
def hello(self):
print('hello world!')
main.py
from Foo import Foo
from FooNotSingleton import FooNotSingleton
foo = Foo()
foo.hello()
bar = FooNotSingleton()
bar.hello()