Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading