Created
December 22, 2022 19:28
-
-
Save Harduim/8b27daa36f0b74ffee0c5a734640e9c8 to your computer and use it in GitHub Desktop.
Import all submodules of a module, recursively, including subpackages
This file contains 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
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