tags:

views:

572

answers:

5

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?

+5  A: 

You 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")
Manuel Ceron
This has an aliasing issue: an ID obtained at an arbitrary point in the past may now refer to a different object.
chaos
As long as you've maintained a reference to the object, that won't happen. Just the same, this is generally a bad idea.
Glenn Maynard
I agree with many of the other commenters: don't do this. Make your own dictionary of objects.
Ned Batchelder
+13  A: 

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.

chaos
I've been intending to throw away the id reference in the object's `__del__`, do you think that this will make sure things will not break?
cool-RR
+1: Agree: Don't do this. Simply create a proper dictionary of objects with proper keys -- you'll be a lot happier.
S.Lott
@cool-RR: Yeah, you should be safe with that.
chaos
+1  A: 

eGenix mxTools library does provide such a function, although marked as "expert-only": mx.Tools.makeref(id)

Fabian Neumann
+4  A: 

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.

Ken
Nailed it. Can you please edit the answer to quote a few lines about the weakref module, just for StackOverflow posterity?
cool-RR
No problem. Done. :)
Ken
+1  A: 

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.

http://www.friday.com/bbum/2007/08/24/python-di/

Unknown