Storing 'unhashable' types in dictionaries by address

Ed Avis ed at membled.com
Sun May 25 18:09:53 EDT 2003


"Tim Peters" <tim_one at email.msn.com> writes:

>>I hope the intent is clear - I want to look up by object identity and
>>not by the contents of the list.

>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.

Clearly, though, you can't then call keys() on the dictionary and get
back an original object, only its address.  However you can imagine a
special dictionary-like class that automatically calls id on keys that
need it, internally keeps track of the object corresponding to each
address, and then returns keys that are live objects.  In other words
it would present an interface that lets you shove objects into and out
of dictionaries - as keys or as values - with impunity.

I didn't see such a class in the Python standard library but does one
exist somewhere?  (You said you did not know of any but maybe others
will.)

>print new_list in d.keys()    # prints 0 (2.2.2) or False (2.3)
>print new_list in d           # the same, but much more efficient
>print d.has_key(new_list)     # also much more efficient

>Do note the last two lines, which didn't appear in your original.

I'm still using Python 1.5.2 (at least on the box I post to newsgroups
with) so I have an excuse for one of them :-(.

-- 
Ed Avis <ed at membled.com>




More information about the Python-list mailing list