Created
March 13, 2025 15:39
-
-
Save jrialland/595ade394fd59d7227e57e35906d397e to your computer and use it in GitHub Desktop.
This code snippet defines a function import_submodules that imports all submodules of a given module recursively, including subpackages.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from types import ModuleType | |
def import_submodules(module: ModuleType) -> None: | |
""" | |
Import all submodules of a module, recursively, including subpackages. | |
:param module: module (package) to import submodules of | |
""" | |
import importlib | |
import pkgutil | |
path = getattr(module, "__path__", []) | |
if path: | |
for _loader, name, is_pkg in pkgutil.iter_modules(path): | |
full_name = module.__name__ + "." + name | |
print("Importing", full_name) | |
submodule = importlib.import_module(full_name) | |
if is_pkg: | |
import_submodules(submodule) | |
if __name__ == "__main__": | |
import_submodules(__import__("a")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If using pyinstaller, do not forget to add --collect-submodules MODULENAME so pyinstaller will not forget to add the submodules in the executable.