Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2 __getattr__ max recursion depth

Tags:

python

getattr

for example i use this code:

class A(object):
    def __init__(self):
        self.dict1 = {
            'A': 3,
            'B': self.A}
    def __getattr__(self, key):
        if key in self.dict1:
            return self.dict1[key]
a = A()

and when it's runned it throws maximum recursion depth exceeded. Can someone please tell me what am i doing wrong here

like image 607
M1k3 Avatar asked Jan 16 '16 15:01

M1k3


People also ask

How do you fix maximum recursion depth exceeded?

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.

What is the maximum depth recursion limit in Python?

Python uses a maximum recursion depth of 1000 to ensure no stack overflow errors and infinite recursions are possible.

How do you overcome maximum recursion depth in Python?

The Python interpreter limits the recursion limit so that infinite recursions are avoided. 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.

Is there a limit to the depth of the recursive calls?

The maximal number of nested calls (including the first one) is called recursion depth. In our case, it will be exactly n . The maximal recursion depth is limited by JavaScript engine. We can rely on it being 10000, some engines allow more, but 100000 is probably out of limit for the majority of them.


1 Answers

The reference to self.dict1 inside your __getattr__ method causes __getattr__ to be called again, and so on, hence the infinite recursion. The only safe way to access attributes of self inside __getattr__ is by using references to self.__dict__. Try

def __getattr__(self, key):
    if key in self.__dict__['dict1']:
        return self.__dict__['dict1'][key]

Note also that the absence of an else clause will mean undefined attributes appear to have the value None.

like image 170
holdenweb Avatar answered Sep 27 '22 17:09

holdenweb