Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum recursion depth error in the python function

I am getting maximum recursion depth error in the line if hasattr(self, '_ubuffer'). Can anyone see what am I doing wrong here? Whole code of the function is:

def __getattr__(self, name):
        if hasattr(self, '_ubuffer'):
            buffer = object.__getattribute__(self,'_ubuffer')
            if name in buffer.dtype.names:
                return buffer.data[name]
        return object.__getattribute__(self,name)
like image 428
M_global Avatar asked Aug 24 '14 11:08

M_global


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.

How do I fix RecursionError maximum recursion depth exceeded while calling a Python object?

A Python RecursionError exception is raised when the execution of your program exceeds the recursion limit of the Python interpreter. Two ways to address this exception are increasing the Python recursion limit or refactoring your code using iteration instead of recursion.

What is maximum recursion depth?

The recursion limit is usually 1000.

How do you find the recursion depth in Python?

To get the current value of the recursion limit in Python, we will import sys module, and then we will use “sys. getrecursionlimit()” to get the current recursion limit.


2 Answers

hasattr calls __getattr__ which would cause the recursion. From the docs:

hasattr(object, name) The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.) [my emphasis]

One way to get around this problem might be to replace if hasattr(self, '_ubuffer') with something like if '_ubuffer' in self.__dict__.

like image 73
Alex Riley Avatar answered Oct 06 '22 16:10

Alex Riley


You can use the superclass implementation for regular attribute access:

def __getattr__(self, name):
    try:
        buffer = super(MyClass, self).__getattr__('_ubuffer')
    except AttributeError:
        raise AttributeError('Attribute {} not found.'.format(name))

    if name in buffer.dtype.names:
        return buffer.data[name]
    else:
        raise AttributeError('Attribute {} not found.'.format(name))
like image 26
Maciej Gol Avatar answered Oct 06 '22 16:10

Maciej Gol