Inverse of id()?
Alex Martelli
aleax at mac.com
Sun May 20 00:03:50 EDT 2007
Paul McGuire <ptmcg at austin.rr.com> wrote:
> Is there an inverse function to the builtin 'id'? The poster who
No, there isn't.
> Now is there anything better than this search technique to get back a
> variable, given its id?
For your own classes/types, you could override __new__ to maintain a
class-wide (or even wider) weakref.WeakValueDictionary with id as the
key and the instance as the (weakly held) value. For the general case,
this wouldn't work -- however as your "search technique" checks globals
only, it's pretty weak (it wouldn't find a value that's only held as an
item in a list even if that list were global, for example). You might
do a bit better by checking through gc.get_objects(), but that won't get
objects of many types, such as int, float, str...
Alex
More information about the Python-list
mailing list