1

I found this searching for singleton concepts in Python. What I wonder about is why self._instance = super(Singleton, self).__new__(self)doesn't cause an infinte loop. I thought that calling __new__ would start a kind of recursion, as self._instanceshould not have been set then.

Where's my mistake?

class Singleton(object):
    _instance = None
    def __new__(self):
        if not self._instance:
            self._instance = super(Singleton, self).__new__(self)
        return self._instance
Xiphias
  • 4,468
  • 4
  • 28
  • 51

2 Answers2

3

This, actually, calls object.__new__, not the Singleton.__new__, so there is no recursion.

Alexander Zhukov
  • 4,357
  • 1
  • 20
  • 31
  • Isn't `Singleton.__new__()` supposed to return an instance of `Singleton`? But as you mentioned, you get an instance of `object` when you do `super(Singleton, self).__new__(self)` – Bob Jul 28 '16 at 22:15
2
super(Singleton, self).__new__(self)

means: call __new__ on the superclass of Singleton (which is object).

So it won't call the same __new__ again and as such it won't create an infinite loop.

After returning it'll set self._instance to a value. Next time you call Singleton() it'll return that instance instead.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180