property collections

Robin Becker robin at jessikat.fsnet.co.uk
Mon May 21 23:48:17 CEST 2001


In article <6qlmnqfsrn.fsf at abnoba.intevation.de>, Bernhard Herzog
<bh at intevation.de> writes
>Robin Becker <robin at jessikat.fsnet.co.uk> writes:
...


This looks more interesting. The problem for me is that the actual items
are of a particular PropertyHolder class, but I think it's possible to
create these on the fly.

Thanks for the code.

>This seems to work without cyclic references:
>
>class ItemProxy:
>
>    def __init__(self, parent, index):
>        self.__dict__["_parent"] = parent
>        self.__dict__["_index"] = index
>
>    def __getattr__(self, attr):
>        return self._parent.get_attribute(self._index, attr)
>
>    def __setattr__(self, attr, value):
>        self._parent.set_attribute(self._index, attr, value)
>
>class Parent:
>
>    def __init__(self):
>        self.items = {}
>
>    def __getitem__(self, index):
>        return ItemProxy(self, index)
>
>    def set_attribute(self, index, attr, value):
>        item = self.items.get(index)
>        if item is None:
>            item = self.items[index] = {}
>        item[attr] = value
>
>    def get_attribute(self, index, attr):
>        item = self.items.get(index)
>        if item is not None and item.has_key(attr):
>            return item[attr]
>        return getattr(self, attr)
>
>
>Sample session:
>
>$ python1.5 -i itemproxy.py 
>>>> p = Parent()
>>>> p.a = 1
>>>> p.b = 2
>>>> p[1].a = 0.5
>>>> p[1].a
>0.5
>>>> p[1].b
>2
>>>> p[2].a
>1
>>>> p[2].b
>2
>>>> 
>
>
>The trick here is that the parent does not have any references to the
>objects returned by the __getitem__ method, so there are no cyclic
>references.
>
>

-- 
Robin Becker



More information about the Python-list mailing list