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 ?

4
  • 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? Commented Apr 7, 2022 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.) Commented Apr 7, 2022 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. Commented Apr 7, 2022 at 14:48
  • 1
    Why don't you just do that, then? setattr(CustomClass, item.name) = type(item.classname, (), item.attributes) Commented Apr 7, 2022 at 17:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.