Skip to content

Instantly share code, notes, and snippets.

@nnnewb
Created February 2, 2019 08:58
Show Gist options
  • Save nnnewb/f1744e3611ea0c92976439fd4fded104 to your computer and use it in GitHub Desktop.
Save nnnewb/f1744e3611ea0c92976439fd4fded104 to your computer and use it in GitHub Desktop.
recursive import package, for sure all sub-modules had been executed, ready for other operation
# compatibility: python 3.6+
import types
import typing
from importlib import import_module
from pkgutil import walk_packages
def import_recursive(pkg: typing.Type[types.ModuleType]) -> typing.Sequence[typing.Type[types.ModuleType]]:
"""
递归导入指定包下所有模块
:return:
"""
modules = []
for finder, name, is_pkg in walk_packages(pkg.__path__):
mod = import_module('.'.join((pkg.__name__, name)))
modules.append(mod)
if is_pkg:
import_recursive(mod)
return modules
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment