1 year ago

#387697

test-img

ibi0tux

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

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 ?

python

class

scope

dynamic-class-creation

0 Answers

Your Answer

Accepted video resources