In python, is it better that using the singleton pattern instead of using global variable?
class Singleton(type):
def __call__(self, *args, **kwargs):
if 'instance' not in self.__dict__:
self.instance = super(Singleton, self).__call__(*args, **kwargs)
return self.instance
or just make a global variable:
SINGLETON_VARIABLE = None
def getSingleton():
if SINGLETON is None:
SINGLETON_VARIABLE = SOME_ININ_CLASS()
return SINGLETON_VARIABLE
Is it necessary to complicate the life to make a singleton pattern? Thank you in advance.
The problem with the global variable approach would be that you can always access that variable and modify its content, so it would be a "weaker" form of the Singleton pattern. Also, if you have more than one Singleton class, you have to define a function and a global variable for each, so it ends up being messier than the pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With