Is it possible to dereference variable id's?

Here's a utility function based on a comment made by "Tiran" in the discussion Hophat Abc referenced that will work in both Python 2 and 3:

import _ctypes

def di(obj_id):
    """ Inverse of id() function. """
    return _ctypes.PyObj_FromPtr(obj_id)

if __name__ == '__main__':
    a = 42
    b = 'answer'
    print(di(id(a)))  # -> 42
    print(di(id(b)))  # -> answer

Not easily.

You could recurse through the gc.get_objects() list, testing each and every object if it has the same id() but that's not very practical.

The id() function is not intended to be dereferenceable; the fact that it is based on the memory address is a CPython implementation detail, that other Python implementations do not follow.


There are several ways and it's not difficult to do:

In O(n)

In [1]: def deref(id_):
   ....:     f = {id(x):x for x in gc.get_objects()}
   ....:     return f[id_]

In [2]: foo = [1,2,3]

In [3]: bar = id(foo)

In [4]: deref(bar)
Out[4]: [1, 2, 3]

A faster way on average, from the comments (thanks @Martijn Pieters):

def deref_fast(id_):
    return next(ob for ob in gc.get_objects() if id(ob) == id_)

The fastest solution is in the answer from @martineau, but does require exposing python internals. The solutions above use standard python constructs.