Modifying an instances dict to change attribute lookup

jslowery at gmail.com jslowery at gmail.com
Mon Feb 20 10:51:56 EST 2006


Hmm, I know this is something fundamental about how Python implements
predicate dispatch, but for some reason I believed that this would
work:

class delegate_dict(dict):
    def __init__(self, orig, deleg):
        dict.__init__(self, orig)
        self.deleg = deleg

    def __getitem__(self, name):
        print 'here:', name
        try:
            v = dict.__getitem__(self, name)
        except KeyError:
            return self.deleg.__getitem__(name)
        return v

def delegate(target, source):
    target.__dict__ = delegate_dict(target.__dict__, source.__dict__)

As a simple usage, give:


class A(object):
    pass

class B(object):
    def __init__(self, o):
        delegate(self, o)

a = A()
a.test = 1
b = B(a)
print b.__dict__.__getitem__('test')

# This goes down in flames
print b.test


And then a dumb example showing the concept I assumed was a given:

class C(object):
    pass

c = C()
c.x = 1
assert c.__dict__.__getitem__('x') == c.x

Could someone please tell me why the first example using a customized
dict does not perform as advertised?




More information about the Python-list mailing list