Maximum recursion depth exceeded while calling a Python object

See Python: Tips and Tricks for similar articles.

When working with Python properties, you might find yourself getting a “maximum recursion depth exceeded while calling a Python object” error. Here’s an example of code that will cause this error:

class Person:
    def __init__(self, name):
        self.name = name
    
    def set_name(self, name):
        self.name = name
        
    def get_name(self):
        return self.name
    
    name = property(get_name, set_name)


serena = Person('Serena')

We’ve used the property() function to tell Python that the way to get the value of self.name is to call the get_name() function. But within the get_name() function, we try to return self.name. To find out the value of self.name, Python calls the get_name() function again, which again tries to return self.name. And we find ourselves in an endless loop: Recursive get_name()

The fix is to use a pseudo-private attribute: _name and use get_name() to retrieve self._name and set_name() to set self._name, like this:

class Person:
    def __init__(self, name):
        self._name = name

    def set_name(self, name):
        self._name = name

    def get_name(self):
        return self._name

    name = property(get_name, set_name)


serena = Person("Serena")
print(serena.name)

serena.name = "Serena Williams"
print(serena.name))

This will print:

Serena
Serena Williams