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!
3
  • What is the purpose of storing the instance? Commented May 6, 2021 at 6:45
  • 3
    Avoid using eval. Commented May 6, 2021 at 6:46
  • 1
    "How can I store an instance of a class in a string" Use an actual object serialization format. The fact that this works with most built-in types doesn't mean you should actually use it this way. Use pickle. Commented May 6, 2021 at 7:06

2 Answers 2

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

yup, this is way that it is supposed to be done, but the user can pass their own classes (creating a very simple data structure using setattr and getattr)
@KetZoomer this is definitely not the way it's supposed to be done
@juanpa.arrivillaga yup, I know :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.