weakrefs, threads,, and object ids
jeremy.r.fishman at gmail.com
Sun Jun 14 21:00:33 CEST 2009
I'm using weakrefs in a small multi-threaded application. I have been
using object IDs as dictionary keys with weakrefs to execute removal
code, and was glad to find out that this is in fact recommended
> This simple example shows how an application can use objects IDs to retrieve
> objects that it has seen before. The IDs of the objects can then be used in other
> data structures without forcing the objects to remain alive, but the objects can
> still be retrieved by ID if they do.
After reading this, I realized it made no explicit mention of thread
safety in this section, whereas other sections made a note of correct
practice with threads. The docs for the id() function specify
> Return the identity of an object. This is guaranteed to be unique among
> simultaneously existing objects. (Hint: it's the object's memory address.)
While guaranteed unique for simultaneously existing objects, how often
will an object assume an ID previously held by former object? Given
that the ID is a memory address in Python's heap, I assume the answer
is either not often, or very often.
Specifically, I'm wondering if the case can occur that the callback
for a weakref is executed after another object has been allocated with
the same object identifier as a previous object. If such an object is
inserted into a module-level dictionary, could it over-write a
previous entry with the same identifier and then get deleted whenever
the weakref callback happens to fire?
On a related note, what is a recommended way to obtain a weak
reference to a thread?
More information about the Python-list