Is it possible to dereference variable id's?

Hophat Abc picture Hophat Abc · Feb 21, 2013 · Viewed 17.4k times · Source

Can you dereference a variable id retrieved from the id function in Python? For example:

dereference(id(a)) == a

I want to know from an academic standpoint; I understand that there are more practical methods.

Answer

martineau picture martineau · Feb 21, 2013

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