Alex
Alex

Reputation: 487

Usage of super in singleton

class Singleton(object):
  def __new__(cls, *args, **kw):
      if not hasattr(cls, '_instance'):
        orig = super(Singleton, cls)
        cls._instance = orig.__new__(cls, *args, **kw)
      return cls._instance

Can someone give detailed explanation of what happens here >> super(Singleton, cls) for what cls argument is passed?

Upvotes: 2

Views: 766

Answers (1)

Lauritz V. Thaulow
Lauritz V. Thaulow

Reputation: 50995

The cls attribute passed in to the __new__ method is a reference to the Singleton class (cls == Singleton), but if you subclassed Singleton and instantiated that subclass, cls would be a reference to the subclass instead.

super needs to know both the current class (Singleton) and the subclass whose class hierarchy it's traversing (cls) to compute the next class in the class hierarchy, but in your case they're always the same since Singleton does not have any subclasses.

To elaborate on why it is necessary to pass cls, let's assume that these classes all have simple pass-through __new__ methods that simply call their super methods and return the result.

class A(object): pass
class B(object): pass
class C(A, B): pass

Then C.__new__ calls super(C, cls).__new__, which is equivalent to A.__new__. Now here you want super(A, cls).__new__ to be equivalent to B.__new__, not object.__new__. But the only way super can find that out is by being told that the start was at C, not at A.

Since in your case the only superclass is object, orig.__new__ is equivalent to object.__new__, and it's passed cls so that it will know what class it should instantiate.

Upvotes: 3

Related Questions