Skip to content

Instantly share code, notes, and snippets.

@breeze1990
Last active September 14, 2022 04:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breeze1990/0253cb96ce04c00cb7a67feb2221e95e to your computer and use it in GitHub Desktop.
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
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