Search code examples
pythonpython-3.xmodulepython-importglobal

How do you get all the classes in another package so they can be instantiated in Python3?


I read the question "Importing a whole folder of python files", but it does not include a way to do it without one import per file.

Beside the requirement of avoiding several imports, it is required that the number of classes have nothing to do with the amount of code written. I also want to avoid "from source import *" from being in the code, but am not against it.

I have tried this.

from system.models import *

but that results in

model = globals()[class_name](labels.size()[:-1], labels.size()[-1])

TypeError: 'module' object is not callable

I have also tried this

import sys 
sys.path.insert(0, r'../system/models')

but that results in the globals not containing the classes.

The ultimate goal is, given a folder designated as a python package, to get all the classes in the python files contained in that package.


Solution

  • I was able to load the class object dynamically with the following code.

        classes = []
        package = models
        for importer, modname, _ in pkgutil.iter_modules(package.__path__):
            module = importlib.import_module(f"{package.__name__}.{modname}")
            for name, obj in inspect.getmembers(module):
                if inspect.isclass(obj) and obj.__module__ == module.__name__:
                    classes.append(obj)
    

    Then take any class object from classes and you can create an instance of it like this.

            new_object = class_object()