Last active
October 22, 2015 04:31
-
-
Save AlecTaylor/5837a5329f76383e1294 to your computer and use it in GitHub Desktop.
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 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 | |
def create_symbol_module_d(module_name_module_d, include=None, exclude=None): | |
inv_res = {} | |
for mod in module_name_module_d.itervalues(): | |
for sym in dir(mod): | |
if include and sym in include: | |
inv_res[sym] = mod | |
elif exclude and sym not in exclude: | |
inv_res[sym] = mod | |
else: | |
inv_res[sym] = mod | |
return inv_res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment