Skip to content

Instantly share code, notes, and snippets.

@nchaly
Created May 25, 2024 04:40
Show Gist options
  • Select an option

  • Save nchaly/5c041d9602cb6c591e250d4b07bd8393 to your computer and use it in GitHub Desktop.

Select an option

Save nchaly/5c041d9602cb6c591e250d4b07bd8393 to your computer and use it in GitHub Desktop.
import submodules
def import_submodules(module: ModuleType, level: int = 1, modules_only: bool = True) -> List[str]:
"""Import all submodules of a module, recursively.
Args:
modules_only: If set to True, only modules are imported. If False, packages are
imported as well.
module: Module/package which sub-modules should be imported.
level: Limit import depth. Set to zero or negative to import all level.
For example the following structure is present:
.. code-block::
module_a # root package
a1
a2
tests # package
t1
t2
After `import_submodules(module_a, level=1)`, only `a1` and `a2` would be imported.
If you set level to 2, then `a1`, `a2`, `t1`, `t2` are imported.
If additionally `modules_only` is set to False, then also `module_a.tests` package
is imported as well.
Returns:
List of actually imported sub-modules.
"""
level = max(level, 0)
if not module:
raise ValueError("Module should be provided.")
root_module_name = module.__name__ + "."
len_mod_name = len(root_module_name)
imported = []
for _, module_name, is_package in pkgutil.walk_packages(module.__path__, root_module_name):
# test for level
if level > 0:
current_level = len(module_name[len_mod_name:].split("."))
if current_level > level:
continue
# test for package
if is_package and modules_only:
continue
importlib.import_module(module_name)
imported.append(module_name)
return imported
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment