2

How can I store an instance of a class in a string? I tried eval, but that didn't work and threw SyntaxError. I would like this to work for user-defined classes and built-in classes (int, str, float).

Code:

class TestClass:
    def __init__(self, number):
        self.number = number

i = TestClass(14)
str_i = str(i)
print(eval(str_i)) # SyntaxError
print(eval("jkiji")) # Not Defined
print(eval("14")) # Works!
print(eval("14.11")) # Works!
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
KetZoomer
  • 2,701
  • 3
  • 15
  • 43

2 Answers2

3

The convention is to return a string with which you could instantiate the same object, if at all reasonable, in the __repr__ method.

class TestClass:
    def __init__(self, number):
        self.number = number
    def __repr__(self):
        return f'{self.__class__.__name__}({self.number})'

Demo:

>>> t = TestClass(14)
>>> t
TestClass(14)
>>> str(t)
'TestClass(14)'
>>> eval(str(t))
TestClass(14)

(Of course, you should not actually use eval to reinstantiate objects in this way.)

timgeb
  • 76,762
  • 20
  • 123
  • 145
2

You can also use the pickle built-in module to convert an object to a byte string and back:

import pickle

class TestClass:
    def __init__(self, number):
        self.number = number

t1 = TestClass(14)
s1 = pickle.dumps(t1)
t2 = pickle.loads(s1)

then

print(t2.number)

will print

14
Selcuk
  • 57,004
  • 12
  • 102
  • 110