Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Recursion with __setattr__

Thread Tools

Recursion with __setattr__

Chris Young
Posts: n/a
Operating Ubunutu Linux 5.04 on iMac 333mhz
Python 2.4.1 in IDLE 1.1.1

In trying to create a interactive drawing framework in Python I came across
the idea of binding attributes of one object to attributes of another.

The way it works is when obj1.attr1 is set obj2.attr2 should have it's
__setattr__ method called as well. But it ends up giving me a recursion error.

The attribute synchronization is shown below:


def sync(attr1,obj1,obj2,attr2=None):
"""Synchronize attribute access

name of attribute to synchronize
(optional) attribute name to use when setting second object.
if not attr2: attr2 = attr1
# rename old __setattr__'s
obj1.__old_setattr__ = obj1.__setattr__
obj2.__old_setattr__ = obj2.__setattr__
except AttributeError: pass
# modify mirrored attributes on attribute change
def hook_setattr(inst):
# Hey! Only classes have special methods!
class sethook(inst.__class__):
def __setattr__(self,name,value):
except AttributeError: pass
if name in self.__syncdict__:
entry = self.__syncdict__[name]
for mirror,attr in entry: pass
# recursion error here: setattr(mirror,attr,value)
#sethook.__name__ = inst.__class__.__name__ # magic?
inst.__class__ = sethook
# append synchronization info
except AttributeError:
obj1.__syncdict__ = {attr1: [(obj2,attr2)]}
except AttributeError:
obj2.__syncdict__ = {attr2: [(obj1,attr1)]}
# make the magic work

When I try to call this like sync('attr',obj,obj2) I get a recursion error.
I could understand this happening if I was calling setattr on itself, but
why the other object?

Any help is greatly appreciated. Also, any pointers on efficiency or easier
ways is also welcome. Thanks in

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Setting an attribute without calling __setattr__() Joshua Kugler Python 12 04-29-2008 07:20 PM
Bypassing __setattr__ for changing special attributes George Sakkis Python 7 02-27-2007 12:11 PM
Mixing custom __setattr__ method and properties in new style classes L.C. Rees Python 3 02-08-2006 05:35 PM
__getattr__, __setattr__ Thomas Heller Python 3 10-20-2005 04:50 PM
__setattr__ and __getattr__ with derived classes Anand Python 0 12-18-2003 09:36 PM