Search code examples
pythonctypescpython

Check if an object id exists in Python


Simple: I have an Python object id, and I want to check if there is an object with that id.

From this SO answer, you can get an existing object by id with

import ctypes
a = 10
object_id = id(a)
ctypes.cast(object_id, ctypes.py_object).value

But it hangs when called with a arbitrary object_id, so that's an impractical solution.


Solution

  • To do this, you'd need an exhaustive enumeration of all Python objects. Otherwise, it's impossible to tell the difference between an object and a memory region that just happens to look like an object.

    Unfortunately, there isn't such an exhaustive list. The closest thing is probably gc.get_objects(), which returns a list of all objects tracked by the garbage collector (excluding the list itself). You could search that for an object matching your ID, but things like x = 1; print x in gc.get_objects() won't find the object.