Python convert string back to object

I have an object:

c = Character(...)

I convert it to a string by using:

p = "{0}".format(c)
print(p)
 
>>> <Character.Character object at 0x000002267ED6DA50>

How do i get the object back so i can run this code?

p.get_name()

>Solution :

You absolutely can if you are using CPython (where the id is the memory address). Different implementations may not work the same way.

>>> import ctypes
>>> class A:
...   pass
... 
>>> a = A()
>>> id(a)
140669136944864
>>> b = ctypes.cast(id(a), ctypes.py_object).value
>>> b
<__main__.A object at 0x7ff015f03ee0>
>>> a is b
True

So we’ve de-referenced the id of a back into a py_object and snagged its value.

Leave a Reply