Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, using singleton pattern or just global variable

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.

like image 478
perigee Avatar asked Aug 21 '14 14:08

perigee


1 Answers

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.

like image 81
bconstanzo Avatar answered Sep 16 '22 23:09

bconstanzo