Let's say I have an id of a Python object, which I retrieved by doing id(thing). How do I find thing again by the id number I was given?
views:
572answers:
5You can use the gc module to get all the objects currently tracked by the Python garbage collector.
import gc
def objects_by_id(id_):
for obj in gc.get_objects():
if id(obj) == id_:
return obj
raise Exception("No found")
Short answer, you can't.
Long answer, you can maintain a dict for mapping IDs to objects, or look the ID up by exhaustive search of gc.get_objects(), but this will create one of two problems: either the dict's reference will keep the object alive and prevent GC, or (if it's a WeakValue dict or you use gc.get_objects()) the ID may be deallocated and reused for a completely different object.
Basically, if you're trying to do this, you probably need to do something differently.
eGenix mxTools library does provide such a function, although marked as "expert-only": mx.Tools.makeref(id)
You'll probably want to consider implementing it another way. Are you aware of the weakref module?
(Edited) The Python weakref module lets you keep references, dictionary references, and proxies to objects without having those references count in the reference counter. They're like symbolic links.
Just mentioning this module for completeness. This does what you want without looping throughout every object in existence. It will obviously crash if the object isn't there anymore.