Menu Close

How to get object by id() with Python?

Sometimes, we want to get object by id() with Python.

In this article, we’ll look at how to get object by id() with Python.

How to get object by id() with Python?

To get object by id() with Python, w ecan use the ctypes module.

For instance, we write

import ctypes

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

to get the object a‘s ID with id(a).

Then we get the object by the ID with

ctypes.cast(id(a), ctypes.py_object)

Finally, we get the object’s value with value.

Conclusion

To get object by id() with Python, w ecan use the ctypes module.

Posted in Python, Python Answers