property collections
Bernhard Herzog
bh at intevation.de
Mon May 21 14:42:36 EDT 2001
Robin Becker <robin at jessikat.fsnet.co.uk> writes:
> In article <9e90k20aiu at enews1.newsguy.com>, Alex Martelli
> <aleaxit at yahoo.com> writes
> >"Robin Becker" <robin at jessikat.fsnet.co.uk> wrote in message
> >news:g44pZKATy8B7Ewa2 at jessikat.fsnet.co.uk...
> > ...
> >> My solutions seem to involve elements which need to refer to the parent
> >> and thus create a loop.
> >
> >Not sure I understand your general problem, but, regarding
> >this last item, have you tried the (new in 2.1) weak refs...?
> >
> >
> >Alex
> well now I would certainly use weak refs if that were feasible for all,
> but some people are still using 1.5.2 and so I still have to worry about
> memory loops. Weak refs are exactly the python only solution for this
> sort of acquisition style object.
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.
--
Intevation GmbH http://intevation.de/
Sketch http://sketch.sourceforge.net/
MapIt! http://mapit.de/
More information about the Python-list
mailing list