« Back to Index

[Dynamically import modules from a package in Python]

View original Gist on GitHub

Tags: #python

Dynamically import modules from a package in Python.py

import pkgutil


def get_test_routes():
	"""
    imagine 'routes' contains foo.py bar.py and baz.py
    and in each of those files is a 'tests' variable
    we want to import each 'tests' variable into this file's scope
    """
    from tests import routes
    test_modules = []
    for importer in pkgutil.iter_modules(routes.__path__):
        if importer.ispkg is False:
            print(f"Loading test routes for {importer.name}")
            test_modules.append(importer.module_finder.find_module(importer.name).load_module(importer.name))
    return test_modules


test_modules = get_test_routes()
for mod in test_modules:
    print(len(mod.tests))
    
# construct a single list made up of the contents of the multiple 'tests' lists
host_endpoint_tests = [test for mod in get_test_routes() for test in mod.tests]