Skip to content

Instantly share code, notes, and snippets.

@Harduim
Created December 22, 2022 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Harduim/8b27daa36f0b74ffee0c5a734640e9c8 to your computer and use it in GitHub Desktop.
Save Harduim/8b27daa36f0b74ffee0c5a734640e9c8 to your computer and use it in GitHub Desktop.
Import all submodules of a module, recursively, including subpackages
def import_submodules(package, recursive=True):
"""Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for _, name, is_pkg in pkgutil.walk_packages(package.__path__):
full_name = package.__name__ + "." + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment