Python change the scope of classes dynamically created with type() function

202 Views Asked by At

I have a factory class with a method that generates classes dynamically. This class is within a factory.py file.

class Factory:
    def __init__(self, ast):
        self.ast = ast
        self.classes = {}
    
    def run(self):
        for item in self.ast:
            self.classes[item.name] = type(item.classname, (), item.attributes)

Quite simple. The problem is that the generated classes are prefixed with factory. e.g. <class 'factory.MyClass'> or <class 'factory.AnotherClass'>.

I would like to be able to change the scope in which these classes are defined, for instance to something like that :

<class 'CustomClasses.MyClass'>

But it seems that the prefix depends on the module in which the type() function is called. Is there any way to change this behavior ?

0

There are 0 best solutions below