vendredi 18 janvier 2019

Is it possible to instantiate a class from a string variable in python?

Let's say I have a string that holds a valid python class (not a class name). E.g.:

class_template = """
class MyClass(object):
    def __init__(self, name):
         self.name = name

    def print_name(self):
        print('My name is: ' + self.name)

    def add_whatever(a, b):
        return a + b
"""

Is it possible in python to implement a function (string_to_class in the example below) that receives this string and creates a python class out of it so I can instantiate the class later on?

class_template = """
class MyClass(object):
    def __init__(self, name):
         self.name = name

    def print_name(self):
        print('My name is: ' + self.name)

    def add_whatever(a, b):
        return a + b
"""

MyClass = string_to_class(class_template)
my_class_instance = MyClass('Ben')

print(MyClass.add_whatever(2, 3))
my_class_instance.print_name()

The output should be:

5
My name is: Ben

One possible solution might be to write out the string to a MyClass.py file and use __import__() to load it. Is there any other (in memory) solution?

Thank you for the answer.





Aucun commentaire:

Enregistrer un commentaire