Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"maximum recursion depth exceeded" when "property" is applied to instance variable "self.x"

Tags:

python

I was reading property(), which I understand is attribute access goes through the method specified in property(). But I got "RuntimeError: maximum recursion depth exceeded", when executed the following code.

class Property(object):

    def __init__(self):
        self.x = "Raj"

    def gettx(self):
        print "getting x"
        return self.x

    def settx(self, val):
        print "Setting x"
        self.x = val

    def dellx(self):
        print "deleting"
        return self.x

    x = property(gettx, settx, dellx, "I'm object property")


p = Property()
print "p.x", p.x
p.x = "R"
print "p.x:", p.x

Is it not possible to apply property in this way. Because it worked fine when 'self.x' changed to self._x and self.__x.

like image 710
rajpy Avatar asked Feb 07 '13 10:02

rajpy


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 you fix recursion limits in Python?

The recursion depth limit in Python is by default 1000 . You can change it using sys. setrecursionlimit() function.

What is the maximum recursion depth in Python?

Due to this, the recursion limit of python is usually set to a small value (approx, 10^4). This means that when you provide a large input to the recursive function, you will get an error. This is done to avoid a stack overflow. The Python interpreter limits the recursion limit so that infinite recursions are avoided.


1 Answers

The error is due to the following infinite recursion loop: you have defined a property x with uses the gettx, settx and deltx access methods, but the access methods themselves try to access the property x (i.e. call themselves).

You should write the code along the following lines:

class Property(object):

    def __init__(self):
        self.__x = "Raj"  # Class private

    def gettx(self):
        print "getting x"
        return self.__x

    def settx(self, val):
        print "Setting x"
        self.__x = val

    def dellx(self):
        print "deleting"
        return self.__x

    x = property(gettx, settx, dellx, "I'm object property")
like image 95
isedev Avatar answered Nov 01 '22 11:11

isedev