Why a recursion happens here?

Viewed 287

Recently I read an interesting discussion on how to make a singleton in Python. One of the solutions was a tricky decorator defining a class inside its code as a substitute for decorated class:

def singleton(class_):
    class class_w(class_):
        _instance = None
        def __new__(class2, *args, **kwargs):
            if class_w._instance is None:
                class_w._instance = super(class_w, class2).__new__(class2, *args, **kwargs)
                class_w._instance._sealed = False
            return class_w._instance
        def __init__(self, *args, **kwargs):
            if self._sealed:
                return
            super(class_w, self).__init__(*args, **kwargs)
            self._sealed = True
    class_w.__name__ = class_.__name__
    return class_w

@singleton
class MyClass(object):
    def __init__(self, text):
        print text
    @classmethod
    def name(class_):
        print class_.__name__

x = MyClass(111)
x.name()
y = MyClass(222)
print id(x) == id(y)

Output is:

111     # the __init__ is called only on the 1st time
MyClass # the __name__ is preserved
True    # this is actually the same instance

It is stated, that if we use super(MyClass, self).__init__(text) inside __init__ of MyClass, we get into recursion.

I tested and indeed the recursion happens. But, as I understand, MyClass inherits object, so super(MyClass, self) should just merely be object, but it turns out that super(MyClass, self) is __main__.MyClass

Could you explain what happens here step by step for me to understand the reasons why the recursion happens?

1 Answers
Related