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
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.
Python uses a maximum recursion depth of 1000 to ensure no stack overflow errors and infinite recursions are possible.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With