pkgutil — Package extension utility

Source code:Lib/pkgutil.py


This module provides utilities for the import system, in particular packagesupport.

classpkgutil.ModuleInfo(module_finder,name,ispkg)

A namedtuple that holds a brief summary of a module’s info.

New in version 3.6.

pkgutil.extend_path(path,name)

Extend the search path for the modules which comprise a package. Intendeduse is to place the following code in a package’s__init__.py:

frompkgutilimportextend_path__path__=extend_path(__path__,__name__)

This will add to the package’s__path__ all subdirectories of directoriesonsys.path named after the package. This is useful if one wants todistribute different parts of a single logical package as multipledirectories.

It also looks for*.pkg files beginning where* matches thename argument. This feature is similar to*.pth files (see thesite module for more information), except that it doesn’t special-caselines starting withimport. A*.pkg file is trusted at facevalue: apart from checking for duplicates, all entries found in a*.pkg file are added to the path, regardless of whether they existon the filesystem. (This is a feature.)

If the input path is not a list (as is the case for frozen packages) it isreturned unchanged. The input path is not modified; an extended copy isreturned. Items are only appended to the copy at the end.

It is assumed thatsys.path is a sequence. Items ofsys.paththat are not strings referring to existing directories are ignored. Unicodeitems onsys.path that cause errors when used as filenames may causethis function to raise an exception (in line withos.path.isdir()behavior).

classpkgutil.ImpImporter(dirname=None)

PEP 302 Finder that wraps Python’s “classic” import algorithm.

Ifdirname is a string, aPEP 302 finder is created that searches thatdirectory. Ifdirname isNone, aPEP 302 finder is created thatsearches the currentsys.path, plus any modules that are frozen orbuilt-in.

Note thatImpImporter does not currently support being used byplacement onsys.meta_path.

Deprecated since version 3.3:This emulation is no longer needed, as the standard import mechanismis now fullyPEP 302 compliant and available inimportlib.

classpkgutil.ImpLoader(fullname,file,filename,etc)

Loader that wraps Python’s “classic” import algorithm.

Deprecated since version 3.3:This emulation is no longer needed, as the standard import mechanismis now fullyPEP 302 compliant and available inimportlib.

pkgutil.find_loader(fullname)

Retrieve a moduleloader for the givenfullname.

This is a backwards compatibility wrapper aroundimportlib.util.find_spec() that converts most failures toImportError and only returns the loader rather than the fullModuleSpec.

Changed in version 3.3:Updated to be based directly onimportlib rather than relyingon the package internalPEP 302 import emulation.

Changed in version 3.4:Updated to be based onPEP 451

pkgutil.get_importer(path_item)

Retrieve afinder for the givenpath_item.

The returned finder is cached insys.path_importer_cache if it wasnewly created by a path hook.

The cache (or part of it) can be cleared manually if a rescan ofsys.path_hooks is necessary.

Changed in version 3.3:Updated to be based directly onimportlib rather than relyingon the package internalPEP 302 import emulation.

pkgutil.get_loader(module_or_name)

Get aloader object formodule_or_name.

If the module or package is accessible via the normal import mechanism, awrapper around the relevant part of that machinery is returned. ReturnsNone if the module cannot be found or imported. If the named module isnot already imported, its containing package (if any) is imported, in orderto establish the package__path__.

Changed in version 3.3:Updated to be based directly onimportlib rather than relyingon the package internalPEP 302 import emulation.

Changed in version 3.4:Updated to be based onPEP 451

pkgutil.iter_importers(fullname='')

Yieldfinder objects for the given module name.

If fullname contains a ‘.’, the finders will be for the packagecontaining fullname, otherwise they will be all registered top levelfinders (i.e. those on both sys.meta_path and sys.path_hooks).

If the named module is in a package, that package is imported as a sideeffect of invoking this function.

If no module name is specified, all top level finders are produced.

Changed in version 3.3:Updated to be based directly onimportlib rather than relyingon the package internalPEP 302 import emulation.

pkgutil.iter_modules(path=None,prefix='')

YieldsModuleInfo for all submodules onpath, or, ifpath isNone, all top-level modules onsys.path.

path should be eitherNone or a list of paths to look for modules in.

prefix is a string to output on the front of every module name on output.

Note

Only works for afinder which defines aniter_modules()method. This interface is non-standard, so the module also providesimplementations forimportlib.machinery.FileFinder andzipimport.zipimporter.

Changed in version 3.3:Updated to be based directly onimportlib rather than relyingon the package internalPEP 302 import emulation.

pkgutil.walk_packages(path=None,prefix='',onerror=None)

YieldsModuleInfo for all modules recursively onpath, or, ifpath isNone, all accessible modules.

path should be eitherNone or a list of paths to look for modules in.

prefix is a string to output on the front of every module name on output.

Note that this function must import allpackages (not all modules!) onthe givenpath, in order to access the__path__ attribute to findsubmodules.

onerror is a function which gets called with one argument (the name of thepackage which was being imported) if any exception occurs while trying toimport a package. If noonerror function is supplied,ImportErrorsare caught and ignored, while all other exceptions are propagated,terminating the search.

Examples:

# list all modules python can accesswalk_packages()# list all submodules of ctypeswalk_packages(ctypes.__path__,ctypes.__name__+'.')

Note

Only works for afinder which defines aniter_modules()method. This interface is non-standard, so the module also providesimplementations forimportlib.machinery.FileFinder andzipimport.zipimporter.

Changed in version 3.3:Updated to be based directly onimportlib rather than relyingon the package internalPEP 302 import emulation.

pkgutil.get_data(package,resource)

Get a resource from a package.

This is a wrapper for theloaderget_data API. Thepackage argument should be the name of a package, in standard module format(foo.bar). Theresource argument should be in the form of a relativefilename, using/ as the path separator. The parent directory name.. is not allowed, and nor is a rooted name (starting with a/).

The function returns a binary string that is the contents of the specifiedresource.

For packages located in the filesystem, which have already been imported,this is the rough equivalent of:

d=os.path.dirname(sys.modules[package].__file__)data=open(os.path.join(d,resource),'rb').read()

If the package cannot be located or loaded, or it uses aloaderwhich does not supportget_data,thenNone is returned. In particular, theloader fornamespace packages does not supportget_data.