espeed espeed - 3 years ago 134
Python Question

How to avoid a recursive loop with __setattr__ and a property setter?

This causes an infinite recursive loop when setattr is called, when trying to set the value for some_prop, which is a property with a setter:

class TypeSystem(object):

def __setattr__(self, key, value):
if the_special_case is True:
# do something
else:
super(TypeSystem,self).__setattr__(key,value)


class Entity(TypeSystem):

@property
def some_prop(self):
some_prop = self.data.get('some_prop')
if some_prop is None and hasattr(self,"some_prop"):
some_prop = self.some_prop
return some_prop

@some_prop.setter
def some_prop(self,value):
self.some_prop = value

>>> entity = Entity()
>>> entity.some_prop = 3


This works fine for normal attributes that aren't defined as properties because Super calls object's setattr to prevent the recursive loop.

But because some_prop isn't pre-defined, it looks like setattr is being invoked instead some_prop's setter so it gets pulled into a loop.

I have tried this as well....

@some_prop.setter
def some_prop(self, value):
super(TypeSystem, self).__setattr__("some_prop", value)


But it still goes into a recursive loop. I'm not seeing how to avoid it.

agf agf
Answer Source

This has nothing to do with __setattr__ or your TypeSystem. Your problem is

@some_prop.setter
def some_prop(self,value):
    self.some_prop = value

That is clearly an infinite loop - you're trying to set the property in the property's setter.

You have the same problem in the getter:

some_prop = self.some_prop

will cause an infinite loop as well -- you're trying to get the property in the property's getter.

You need to use another variable to hold the actual data:

class Entity(TypeSystem):

    @property
    def some_prop(self):
        some_prop = self.data.get('some_prop')
        if some_prop is None and hasattr(self,"_some_prop"):
            some_prop = self._some_prop
        return some_prop

    @some_prop.setter
    def some_prop(self,value):
        self._some_prop = value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download