Using importlib.metadata

Source code: Lib/importlib/metadata.py

3.8 新版功能.

注解

This functionality is provisional and may deviate from the usual version semantics of the standard library.

importlib.metadata is a library that provides for access to installed package metadata. Built in part on Python’s import system, this library intends to replace similar functionality in the entry point API and metadata API of pkg_resources. Along with importlib.resources in Python 3.7 and newer (backported as importlib_resources for older versions of Python), this can eliminate the need to use the older and less efficient pkg_resources package.

By “installed package” we generally mean a third-party package installed into Python’s site-packages directory via tools such as pip. Specifically, it means a package with either a discoverable dist-info or egg-info directory, and metadata defined by PEP 566 or its older specifications. By default, package metadata can live on the file system or in zip archives on sys.path. Through an extension mechanism, the metadata can live almost anywhere.

概述

Let’s say you wanted to get the version string for a package you’ve installed using pip. We start by creating a virtual environment and installing something into it:

  1. $ python3 -m venv example
  2. $ source example/bin/activate
  3. (example) $ pip install wheel

You can get the version string for wheel by running the following:

  1. (example) $ python
  2. >>> from importlib.metadata import version
  3. >>> version('wheel')
  4. '0.32.3'

You can also get the set of entry points keyed by group, such as console_scripts, distutils.commands and others. Each group contains a sequence of EntryPoint objects.

You can get the metadata for a distribution:

  1. >>> list(metadata('wheel'))
  2. ['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'Maintainer', 'Maintainer-email', 'License', 'Project-URL', 'Project-URL', 'Project-URL', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Provides-Extra', 'Requires-Dist', 'Requires-Dist']

You can also get a distribution’s version number, list its constituent files, and get a list of the distribution’s Distribution requirements.

可用 API

This package provides the following functionality via its public API.

Entry points

The entry_points() function returns a dictionary of all entry points, keyed by group. Entry points are represented by EntryPoint instances; each EntryPoint has a .name, .group, and .value attributes and a .load() method to resolve the value. There are also .module, .attr, and .extras attributes for getting the components of the .value attribute:

  1. >>> eps = entry_points()
  2. >>> list(eps)
  3. ['console_scripts', 'distutils.commands', 'distutils.setup_keywords', 'egg_info.writers', 'setuptools.installation']
  4. >>> scripts = eps['console_scripts']
  5. >>> wheel = [ep for ep in scripts if ep.name == 'wheel'][0]
  6. >>> wheel
  7. EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts')
  8. >>> wheel.module
  9. 'wheel.cli'
  10. >>> wheel.attr
  11. 'main'
  12. >>> wheel.extras
  13. []
  14. >>> main = wheel.load()
  15. >>> main
  16. <function main at 0x103528488>

The group and name are arbitrary values defined by the package author and usually a client will wish to resolve all entry points for a particular group. Read the setuptools docs for more information on entry points, their definition, and usage.

Distribution metadata

Every distribution includes some metadata, which you can extract using the metadata() function:

  1. >>> wheel_metadata = metadata('wheel')

The keys of the returned data structure 1 name the metadata keywords, and their values are returned unparsed from the distribution metadata:

  1. >>> wheel_metadata['Requires-Python']
  2. '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'

Distribution versions

The version() function is the quickest way to get a distribution’s version number, as a string:

  1. >>> version('wheel')
  2. '0.32.3'

Distribution files

You can also get the full set of files contained within a distribution. The files() function takes a distribution package name and returns all of the files installed by this distribution. Each file object returned is a PackagePath, a pathlib.Path derived object with additional dist, size, and hash properties as indicated by the metadata. For example:

  1. >>> util = [p for p in files('wheel') if 'util.py' in str(p)][0]
  2. >>> util
  3. PackagePath('wheel/util.py')
  4. >>> util.size
  5. 859
  6. >>> util.dist
  7. <importlib.metadata._hooks.PathDistribution object at 0x101e0cef0>
  8. >>> util.hash
  9. <FileHash mode: sha256 value: bYkw5oMccfazVCoYQwKkkemoVyMAFoR34mmKBx8R1NI>

Once you have the file, you can also read its contents:

  1. >>> print(util.read_text())
  2. import base64
  3. import sys
  4. ...
  5. def as_bytes(s):
  6. if isinstance(s, text_type):
  7. return s.encode('utf-8')
  8. return s

In the case where the metadata file listing files (RECORD or SOURCES.txt) is missing, files() will return None. The caller may wish to wrap calls to files() in always_iterable or otherwise guard against this condition if the target distribution is not known to have the metadata present.

Distribution requirements

To get the full set of requirements for a distribution, use the requires() function:

  1. >>> requires('wheel')
  2. ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"]

Distributions

While the above API is the most common and convenient usage, you can get all of that information from the Distribution class. A Distribution is an abstract object that represents the metadata for a Python package. You can get the Distribution instance:

  1. >>> from importlib.metadata import distribution
  2. >>> dist = distribution('wheel')

Thus, an alternative way to get the version number is through the Distribution instance:

  1. >>> dist.version
  2. '0.32.3'

There are all kinds of additional metadata available on the Distribution instance:

  1. >>> dist.metadata['Requires-Python']
  2. '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
  3. >>> dist.metadata['License']
  4. 'MIT'

The full set of available metadata is not described here. See PEP 566 for additional details.

Extending the search algorithm

Because package metadata is not available through sys.path searches, or package loaders directly, the metadata for a package is found through import system finders. To find a distribution package’s metadata, importlib.metadata queries the list of meta path finders on sys.meta_path.

The default PathFinder for Python includes a hook that calls into importlib.metadata.MetadataPathFinder for finding distributions loaded from typical file-system-based paths.

The abstract class importlib.abc.MetaPathFinder defines the interface expected of finders by Python’s import system. importlib.metadata extends this protocol by looking for an optional find_distributions callable on the finders from sys.meta_path and presents this extended interface as the DistributionFinder abstract base class, which defines this abstract method:

  1. @abc.abstractmethod
  2. def find_distributions(context=DistributionFinder.Context()):
  3. """Return an iterable of all Distribution instances capable of
  4. loading the metadata for packages for the indicated ``context``.
  5. """

The DistributionFinder.Context object provides .path and .name properties indicating the path to search and name to match and may supply other relevant context.

What this means in practice is that to support finding distribution package metadata in locations other than the file system, subclass Distribution and implement the abstract methods. Then from a custom finder, return instances of this derived Distribution in the find_distributions() method.

备注

1

Technically, the returned distribution metadata object is an email.message.EmailMessage instance, but this is an implementation detail, and not part of the stable API. You should only use dictionary-like methods and syntax to access the metadata contents.