This week again I was bitten by the fact that Python doesn't have any form of weak references, and while I was toying with some ideas I came up with the following quick-and-dirty scheme that I thought I'd bounce off this list. I might even volunteer to implement it, if people agree it is worth it:-) We add a new builtin function (or a module with that function) weak(). This returns a weak reference to the object passed as a parameter. A weak object has one method: strong(), which returns the corresponding real object or raises an exception if the object doesn't exist anymore. For convenience we could add a method exists() that returns true if the real object still exists. Now comes the bit that I'm unsure about: to implement this I need to add a pointer to every object. This pointer is either NULL or points to the corresponding weak objectt (so for every object there is either no weak reference object or exactly one). But, for the price of 4 bytes extra in every object we get the nicety that there is little cpu-overhead: refcounting macros work identical to the way they do now, the only thing to take care of is that during object deallocation we have to zero the weak pointer. (actually: we could make do with a single bit in every object, with the bit meaning "this object has an associated weak object". We could then use a global dictionary indexed by object address to find the weak object)
participants (4)
-
Jack Jansen
-
M.-A. Lemburg
-
Tim Peters
-
Vladimir Marangozov