[Python-ideas] weakref.WeakKeyDictionary is (basically) useless

Kevin Norris nykevin.norris at gmail.com
Wed Dec 31 03:50:56 CET 2014


On Tue, Dec 30, 2014 at 9:33 PM, Nils Bruin <bruin.nils at gmail.com> wrote:
> We ran into this for sage (www.sagemath.org) and we implemented
> "MonoDict" with basically the semantics you describe. It is
> implemented as a cython extension class. See:
>
> http://git.sagemath.org/sage.git/tree/src/sage/structure/coerce_dict.pyx#n241
>
> I can confirm your observation that it's hard to get right, but I think our
> implementation by now is both correct and fast. The idiosyncratic
> name reveals its origin in "TripleDict" defined in the same file, which
> was developed first.
>
> Incidentally, we also have a WeakValueDict implementation that is faster
> and a little safer than at least the Python2 version:
>
> http://git.sagemath.org/sage.git/tree/src/sage/misc/weak_dict.pyx
>
> These implementations receive quite a bit of exercise in sage,
> so I would recommend that you look at them before developing
> something from scratch yourself.

This is quite interesting.  Is there any interest in maintaining that
code in a separate library?  Sage is a rather large dependency which,
for better or for worse, has little to do with my own work.  I'm
reluctant to add something that large for a single utility class.  If
there is no such interest, I might consider forking.

In my code, I've worked around it by having the owner class and the
descriptor collude (basically, the owner's instances have a private
attribute which the descriptor uses), but it's far from the cleanest
solution.

--
Kevin Norris


More information about the Python-ideas mailing list