python bijection
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Dec 9 02:09:24 EST 2009
En Sat, 28 Nov 2009 06:30:44 -0300, Joshua Bronson <jabronson at gmail.com>
escribió:
> On Nov 27, 9:36 pm, "Gabriel Genellina" <gagsl-py2 at yahoo.com.ar>
> wrote:
>> En Fri, 27 Nov 2009 15:12:36 -0300, Francis Carr
>> <coldtortuga at gmail.com> escribió:
>>
>> > After much tinkering, I think I have a simpler solution. Just make
>> > the inverse mapping accessible via an attribute, -AND- bind the
>> > inverse of -THAT- mapping back to the original. The result is a
>> > python dict with NO NEW METHODS except this inverse-mapping
>> > attribute. I have posted it on code.activestate.com as <a
>> > href="http://code.activestate.com/recipes/576968/">Recipe 576968:
>> > Flipdict -- python dict that also maintains a one-to-one inverse
>> > mapping</a>
>
>> Just a couple of comments:
>>
>> Instead of:
>> self._flip = dict.__new__(self.__class__)
>> I'd write:
>> self._flip = self.__class__()
>> unless I'm missing something (but see the next point).
>
> How would this not cause infinite recursion?
That goes under "unless I'm missing something" ;)
You're right, it would cause infinite recursion. Not a good idea...
>> Also, although Python's GC is able to handle them, I prefer to avoid
>> circular references like those between x and x._flip. Making
>> self._flip a weak reference (and dereferencing it in the property)
>> should be enough.
>
> If both self._flip and self._flip._flip are weak references, no strong
> references to the inverse mapping survive leaving the constructor
> scope. Unless I'm missing something, only one of these can be a weak
> reference, and then you'd have to do something like this in the
> property to prevent "TypeError: FlipDict is not callable":
>
> @property
> def flip(self):
> try:
> # we're an inverse, self._flip is a weak reference
> return self._flip()
> except TypeError:
> # we're a forward mapping, self._flip is a strong
> reference
> return self._flip
Yes - although I'd explicitely test for a weakref object:
def flip(self):
_flip = self._flip
if isinstance(_filp, weakref.ref):
return _flip()
return _flip
and probably all those internal references to self._flip should become
self.flip too; I've not tested the code but I think it *should* work...
--
Gabriel Genellina
More information about the Python-list
mailing list