0

I am trying to save a class written in string format to a database, then read this and load the class as literal class.

How can I do this?

test = """
class Test:
    def __init__(self, test_name):
        self.test_name = test_name
    
    def print_name(self):
        print(self.test_name)
"""

Test = eval(test)
test_obj = Test(test_name='test1')

It would be better together if I also know how to save the object instance in string format since I will save the instance to the database as well, like saving pickle.

Many thanks.

Isaac Sim
  • 539
  • 1
  • 7
  • 23
  • This doesn't appears to be a great idea to save code as strings… What's the use case for something like this? Why not pickle…? – deceze Dec 01 '20 at 07:32
  • Pickle needs class definition in order to load it. Without the class it will fail to load its data. I want to save the class anytime I want to, like a script in javascript, some of them will be deleted or marked from database so I will use them all in distinct ways.. – Isaac Sim Dec 01 '20 at 07:35
  • @deceze For further explanation, I am developing many machine learning models, and models could be slightly different from each other so I want to save them and use the ones that have the best performance though... – Isaac Sim Dec 01 '20 at 07:36

1 Answers1

1

Almost a duplicate but I had to combine two answers. If you have your class saved in a file - which you probably have - you are in luck:

According to here you want to use the inspect.getsource.

According to here you will then need to call the exec function on the string to retrieve the saved class.

Putting things together:

import inspect

class Test:
    def __init__(self):
        self.a = 1
    def print(self):
        print(self.a)

text = inspect.getsource(Test)
exec(text)

As for retrieving a code of a class that is not saved in the file I didn't find a way and the first linked question's answer suggests that there isn't any.

Shamis
  • 2,544
  • 10
  • 16
  • this causes an error "TypeError: is a built-in class" – Isaac Sim Dec 01 '20 at 08:15
  • this exact `ctrl+c`'d code or your application of this code to your problem? I'm running python 3, this is in a separate source file and it is the only code being run. It works. So I can't reproduce the error. However it seems to me that you are calling the `getsource` on something built-in which is causing the error. As mentioned in the first answer, this only works for a code you have saved in a file. – Shamis Dec 01 '20 at 08:17
  • I am running it on the jupyter notebook, but only source is the above, running in a single cell. – Isaac Sim Dec 01 '20 at 09:09
  • I'm not sure if a jupyter notebook qualifies as having the source saved in a file. I don't use them much. Could you please try running the code in a common .py file? – Shamis Dec 01 '20 at 09:35