11

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.

perigee
  • 9,438
  • 11
  • 31
  • 35

1 Answers1

6

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.

bconstanzo
  • 566
  • 4
  • 10
  • 1
    Thanks a lot, any side-effect with singleton approach? – perigee Aug 21 '14 at 15:55
  • 3
    Hey sorry for the late response, I was a bit overloaded with work and didn't have the extra time to come by. I think the worst the Singleton pattern brings is the extra complexity in the class definition, but that is a price you pay once and then reap the benefits. You seem to have it nailed down already, so I'd just go with it. – bconstanzo Aug 24 '14 at 15:39
  • thank you very much for such comprehensive explanation. – perigee Aug 25 '14 at 13:46