'Import __all__ from Python module given by variable

I wan to import all the functions and class into a module/file of Python in high level file just passing a variable that contains the low level file name.

I have a application with several module like:

__all__ = ['MyClass1', 'my_function1']

class MyClass1():
    pass

def my_function1():
   pass

that previous was import at the high level file as:

from sub_module1 import *
from sub_module2 import *
...


# To direct use, of the different subfiles:
obj1 = MyClass1()
obj2 = MyClass2()

The application became a plugin based and I have to dynamic import all module into a folder and provide direct access to all objects defined into __all__ of those submodules.

The code bellow imports fine the submodules but I don not give my direct access to the directives defined into __all__ of those files.

from os import path
from importlib import import_module

directory_name = ## Define the plugins dir.
for importer, package_name, _ in iter_modules([directory_name]):
    module_specification = importlib.util.spec_from_file_location(
        package_name, path.join(directory_name, package_name + '.py'))
    module_loader = importlib.util.module_from_spec(module_specification)
    module_specification.loader.exec_module(module_loader)

How do I put those object define into __all__ of the submodules inside locals() of the high module?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source