Search code examples
pythonpython-3.xclassinstantiation

Is it possible to dynamic instantiate a class written in a string without the need to write it to a file?


How can I instantiate the class stored in the raw string my_class without having to save this string into a file first?

my_class = r'''class A:
    def print(self):
        print('Hello World')
    '''

my_class_object = string_to_class()

my_class_object.print()

In the code above, I'm looking for an implementation of the function string_to_class() that returns an object of the class inside my_class.

The expected output of the code above is Hello World.


Solution

  • You just need to use exec: it supports dynamic execution of Python code.

    import re 
    def string_to_object(str_class, *args, **kwargs):
        exec(str_class)
        class_name = re.search("class ([a-zA-Z_][a-zA-Z0-9_]*)", str_class).group(1)
        return locals()[class_name](*args, **kwargs)
    

    You can use the string_to_object function to automatically create an object of the specified class:

    my_class = '''
    class A:
        def print(self):
            print("Hello World")
    '''
    a = string_to_object(my_class)
    a.print() # Hello World
    

    You can also build something more complicated:

    my_class = '''
    class B:
        def __init__(self, a, b, c=0, d=1):
            self.a = a
            self.b = b
            self.c = c
            self.d = d
    '''
    b = string_to_object(my_class, 4, 5, c=7)
    print(b.a) # 4
    print(b.b) # 5
    print(b.c) # 7
    print(b.d) # 1
    

    And also:

    class C:
        pass
    
    my_class = '''
    class D(C):
        pass
    '''
    
    d = string_to_object(my_class)