0

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 ?

ucczs
  • 609
  • 5
  • 15
ibi0tux
  • 2,481
  • 4
  • 28
  • 49
  • 1
    Why is what the `type` function returns a problem? If you want to check the `type()` of an instance of `Factory`, then after `from factory import Factory` and `f = Factory()`, `type(f) == Factory` is `True`. If this isn't your problem, then what is it? – Ukulele Apr 07 '22 at 14:35
  • The class name itself does not include `factory`. That's an artifact of how `type.__repr__` is defined. (Even if it did, the name of the class typically doesn't matter *except* for how `__repr__` renders it. It's not related to any variables referring to the class.) – chepner Apr 07 '22 at 14:37
  • Ideally I wish I could have all the classes as attributes of the `CustomClasses` module and make them accessible this way rather than storing them in the local dictionnary. – ibi0tux Apr 07 '22 at 14:48
  • 1
    Why don't you just do that, then? `setattr(CustomClass, item.name) = type(item.classname, (), item.attributes)` – rici Apr 07 '22 at 17:02

0 Answers0