I have a class LabelMapper
(a boost::python
class), which implements the dictionary protocol. I would like to have a proxy class which will use attributes for accessing that dicionary. I've seen many posts for overriding __setitem__
and __getitem__
but I can't seem to get it right.
The naive approach (below) leads to infinite recursion due to self.mapper
invoking LabelMapperProxy.__getattr__
, which in turn needs self.mapper
and so on.
class LabelMapper(object):
def __init__(self): self.map={}
def __getitem__(self,key): return self.map[key]
def __setitem__(self,key,val): self.map[key]=val
def __delitem__(self,key): del self.map[key]
class LabelMapperProxy(object):
def __init__(self,mapper): self.mapper=mapper
def __getattr__(self,key): return self.mapper[key]
def __setattr__(self,key,val): self.mapper[key]=val
def __delattr__(self,key): del self.mapper[key]
lm=LabelMapper()
lm['foo']=123
# construct the proxy
lmp=LabelMapperProxy(mapper=lm)
print lmp.foo # !!! recursion
lmp.bar=456
print lmp.bar,lm['bar']
What is the solution? Perhaps is there such a proxy pre-cooked in the standard library?