Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid infinite recursion with super()?

I have code like this:

class A(object):     def __init__(self):           self.a = 1  class B(A):     def __init__(self):         self.b = 2         super(self.__class__, self).__init__()  class C(B):     def __init__(self):         self.c = 3         super(self.__class__, self).__init__() 

Instantiating B works as expected but instantiating C recursed infinitely and causes a stack overflow. How can I solve this?

like image 301
david4dev Avatar asked Nov 20 '10 21:11

david4dev


People also ask

How do you prevent recursion from being an infinite loop?

To prevent infinite recursion, you need at least one branch (i.e. of an if/else statement) that does not make a recursive call. Branches without recursive calls are called base cases; branches with recursive calls are called recursive cases. Functions can also be mutually recursive.

How can you avoid maximum recursion depth exceeded in comparison?

The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.

How do you fix recursion limits in Python?

The “sys” module in Python provides a function called setrecursionlimit() to modify the recursion limit in Python. It takes one parameter, the value of the new recursion limit. By default, this value is usually 10^3.

Why is recursion not infinite?

If a recursion never reaches a base case, it will go on making recursive calls forever and the program will never terminate. This is known as infinite recursion, and it is generally not considered a good idea. In most programming environments, a program with an infinite recursion will not really run forever.


1 Answers

When instantiating C calls B.__init__, self.__class__ will still be C, so the super() call brings it back to B.

When calling super(), use the class names directly. So in B, call super(B, self), rather than super(self.__class__, self) (and for good measure, use super(C, self) in C). From Python 3, you can just use super() with no arguments to achieve the same thing

like image 133
Thomas K Avatar answered Oct 04 '22 05:10

Thomas K