'di' - the reverse of 'id' in python
id(obj)
returns an integer with object address in python (cPython).
What about the reverse: return python object by address?
Method 1: using gc
The registry of (almost) all python objects is handled by the built-in garbage collector module gc
.
The list of objects can be retrieved using gc.get_objects()
.
We can find the needed object using a lookup dictionary.
import gc
def di(addr):
return {id(i): i for i in gc.get_objects()}[addr]
x = ['hello world']
print(di(id(x)))
But not every object (and not at all times) can be accessed this way. For example, built-in immutable types such as strings, bytes, numbers, are not in the returned list.
Method 2: using ctypes
A faster way is to use ctypes
which nicely cast
s arbitrary addresses into object and data types.
from ctypes import cast, py_object
def di(addr):
return cast(addr, py_object).value
print(di(id("hello world")))
Note that, as many other functions in ctypes
, cast
does not check the validity of the input.
If you pass an invalid pointer, you will likely crash the interpreter.