Storing 'unhashable' types in dictionaries by address

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue May 27 14:49:00 EDT 2003


On Sun, 2003-05-25 at 15:09, Ed Avis wrote:
> "Tim Peters" <tim_one at email.msn.com> writes:

> >The builtin function id(x) returns the "object identity" of x, which
> >you can think of as being its address.
> 
> Thanks for telling me about this (and to the other poster who said the
> same).  So now I can happily associate extra information with
> arbitrary objects by using their address.

One thing to remember is that Python is free to reuse the object id (ie.
address), after that object is deleted. You should take steps to insure
that when you keep track of an object id, that the object itself is not
deleted and the id possibly reused..

A simple technique, when the id() is used as a key in a dictionary, is
to ensure that the corresponding value of that entry should have a
reference to the object (that's the most straightforward way to do it,
anyway).  You can take a tuple of the stuff you want to associate with
the id() key, and the object itself.  ie:

d = {}
a = SomeObject()
b = SomeDataToAssociateWithSomeObject()

d[id(a)] = (b, a)

instead of just

d[id(a)] = b

Of course, it is likely the case when keeping track of ids, that you
might also have a list of the objects, or some other way to keep track
of them all (otherwise, what value is the id()?).  Just want to make
sure this caveat is explicitly stated.

For more info on reuse of ids, and an example of it happening, see the
following post:

http://groups.google.com/groups?q=chad+netzer+difference+in+binding&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=mailman.1052862200.26129.python-list%40python.org&rnum=1


-- 

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)






More information about the Python-list mailing list