how to get back an object from its id() value
CTO
debatem1 at gmail.com
Wed Apr 8 13:02:46 EDT 2009
> I don't know what is the best:
> * using an additional dict and maintaining it
It works, but as you say, is somewhat inelegant.
> * or using the "di" module proposed by CTO
Let me be clear: I am not proposing that you use it. It *does* do what
you
ask- but what you are asking is, all by itself, not a good idea. The
dict
is a vastly superior- and standard- solution to the problem of mapping
one object onto another.
> If "di" is reliable, it seems a good solution for my initial constraint
> which is the impossibility to store anything but strings in my data
> structure.
di is not reliable. Its author says so, and took a lot of heat for not
saying so in Hollywood-sign letters, lit on fire and a thousand feet
tall.
If all you are worried about is storing a string, how about
UserString?
Notice the difference:
>>> from collections import UserString
>>> import weakref
>>> weakref.ref("ABC")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create weak reference to 'str' object
>>> weakref.ref(UserString("ABC"))
<weakref at 0xb7baef2c; to 'UserString' at 0xb7a330ec>
This way you don't have to maintain a dictionary, only store
your string once, and don't have to hack and kludge your way
around id mappings.
More information about the Python-list
mailing list