Skip to content

Instantly share code, notes, and snippets.

@jrialland
Created March 13, 2025 15:39
Show Gist options
  • Save jrialland/595ade394fd59d7227e57e35906d397e to your computer and use it in GitHub Desktop.
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.
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"))
@jrialland
Copy link
Author

If using pyinstaller, do not forget to add --collect-submodules MODULENAME so pyinstaller will not forget to add the submodules in the executable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment