When you want to add to the module search path for a specific package and work with resources included in a package, you need to use pkgutil module from Python library. It includes functions for changing the import rules for Python packages. It is also possible to load non-code resources from files distributed within a package.
Extend the search path for the modules which comprise a package. Intended use is to place the following code in a package’s __init__.py
import pkgutil __path__ = pkgutil.extend_path(__path__, __name__)
extend_path() scans sys.path for directories that include a subdirectory named for the package given as the second argument. The list of directories is combined with the path value passed as the first argument and returned as a single list, suitable for use as the package import path.
find_loader(fullname): Retrieve a module loader for the given fullname.
get_importer(path_item): Retrieve a finder for the given path_item.
Get a loader object for module_or_name.
iter_importers(fullname=''): Yield finder objects for the given module name.
iter_modules(path=None, prefix=''): Yields ModuleInfo for all submodules on path, or, if path is None, all top-level modules on sys.path.
>>> pk = pkgutil.iter_modules() >>> for p in pk: print (p)
walk_packages(path=None, prefix='', onerror=None): Yields ModuleInfo for all modules recursively on path, or, if path is None, all accessible modules.
import pkgutil import sys def explore_package(module_name): loader = pkgutil.get_loader(module_name) for sub_module in pkgutil.walk_packages([loader.filename]): _, sub_module_name, _ = sub_module qname = module_name + "." + sub_module_name print(qname) explore_package(qname)
ModuleInfo(module_finder, name, ispkg): This returns a namedtuple that holds a brief summary of a module’s info.