Last active
September 14, 2022 04:17
-
-
Save breeze1990/0253cb96ce04c00cb7a67feb2221e95e to your computer and use it in GitHub Desktop.
Python: recursively import modules under a folder. https://stackoverflow.com/a/25562415/4107682
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
import importlib | |
import pkgutil | |
def import_submodules(package, recursive=True): | |
""" Import all submodules of a module, recursively, including subpackages | |
:param recursive: bool | |
: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 loader, 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