How do I get an object from the id()-identifier?

Tim Peters tim.one at home.com
Thu May 17 04:42:49 EDT 2001


[Mats Sjoberg]
> I know that I can get a unique identifier (usually the memory
> address) of a python object with the id() function,

It's only unique among the objects alive at the instant you call id(); it's
quite possible to see the same id() many times for distinct objects across
the life of a single program run, and, indeed, garbage collection wouldn't be
doing its job if that weren't true (in the current implementation, id(obj) is
always the memory address of obj, and memory gets resued).

> but how do I get the object back if I only have this identifier?

You cannot, unless you maintain your own dict mapping ids to objects.  If you
do that using a regular dict, that will force the object to stay alive for at
least as long as the dict lives.  In 2.1 you can use a WeakValue dict
instead, and then the id->obj mapping alone won't keep the object alive.  But
then you can bump into the problem described at the start, i.e. that the
address you're holding on to may be reused later for a different object
(albeit an object with a disjoint lifetime).

The best way to map ids to objects is to rethink what you really want to
accomplish until it becomes clear that mapping ids to objects isn't actually
going to get the job done <0.9 wink>.





More information about the Python-list mailing list