Get object by id()? [duplicate]

Solution 1:

If the object is still there, this can be done by ctypes:

import ctypes
a = "hello world"
print ctypes.cast(id(a), ctypes.py_object).value

output:

hello world

If you don't know whether the object is still there, this is a recipe for undefined behavior and weird crashes or worse, so be careful.

Solution 2:

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.

Solution 3:

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")

Solution 4:

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.