Tue, 12 Apr 2005
It doesn't look like you can monkey patch __setattr__ in python
It's a shame, really, because I'm trying to do some adhoc meddling with a hairy inheritance tree and would like to change the __setattr__ for a composed object that gets added up the chain, but only in some of the descendants. Here's a greatly simplified version:
class aClass:
    pass

class Ancestor:
    def __init__(self):
        self.anAttr = aClass()

def custom_setter():
    print "I am being set"

class Mixin:
    def __init__(self):
        setattr(self.anAttr, '__setattr__', custom_setter)

class Youngster(Ancestor, Mixin):
    def __init__(self):
        Ancestor.__init__(self)
        Mixin.__init__(self)

you = Youngster();
you.anAttr.foo = 'bar'
Imagine that Youngster has a few siblings. Most of them have no special designs on the aClass object stored at their anAttr attribute. Youngster, however, would like changes to its anAttr attribute to do something special - in this case, print a message. Unfortunately, setting __setattr__ after the fact just plain doesn't work. You can run the above code, and it doesn't complain, but it doesn't print "I am being set" either. Bummer huh?
[/code]