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.

Added 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__)

For each directory onsys.path that has a subdirectory that matches thepackage name, add the subdirectory to the package’s__path__. This is usefulif one wants to distribute 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 skipping blank lines and ignoring comments, all entriesfound in a*.pkg file are added to the path, regardless of whetherthey exist on 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).

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.iter_importers(fullname='')

Yieldfinder objects for the given module name.

Iffullname contains a'.', the finders will be for the packagecontainingfullname, otherwise they will be all registered top levelfinders (i.e. those on bothsys.meta_path andsys.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.

pkgutil.resolve_name(name)

Resolve a name to an object.

This functionality is used in numerous places in the standard library (seebpo-12915) - and equivalent functionality is also in widely usedthird-party packages such as setuptools, Django and Pyramid.

It is expected thatname will be a string in one of the followingformats, where W is shorthand for a valid Python identifier and dot standsfor a literal period in these pseudo-regexes:

  • W(.W)*

  • W(.W)*:(W(.W)*)?

The first form is intended for backward compatibility only. It assumes thatsome part of the dotted name is a package, and the rest is an objectsomewhere within that package, possibly nested inside other objects.Because the place where the package stops and the object hierarchy startscan’t be inferred by inspection, repeated attempts to import must be donewith this form.

In the second form, the caller makes the division point clear through theprovision of a single colon: the dotted name to the left of the colon is apackage to be imported, and the dotted name to the right is the objecthierarchy within that package. Only one import is needed in this form. Ifit ends with the colon, then a module object is returned.

The function will return an object (which might be a module), or raise oneof the following exceptions:

ValueError – ifname isn’t in a recognised format.

ImportError – if an import failed when it shouldn’t have.

AttributeError – If a failure occurred when traversing the objecthierarchy within the imported package to get to the desired object.

Added in version 3.9.