using.rst 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. .. _using:
  2. ==========================
  3. Using importlib_metadata
  4. ==========================
  5. ``importlib_metadata`` is a library that provides for access to installed
  6. package metadata. Built in part on Python's import system, this library
  7. intends to replace similar functionality in ``pkg_resources`` `entry point
  8. API`_ and `metadata API`_. Along with ``importlib.resources`` in `Python 3.7
  9. and newer`_ (backported as `importlib_resources`_ for older versions of
  10. Python), this can eliminate the need to use the older and less efficient
  11. ``pkg_resources`` package.
  12. By "installed package" we generally mean a third party package installed into
  13. Python's ``site-packages`` directory via tools such as ``pip``. Specifically,
  14. it means a package with either a discoverable ``dist-info`` or ``egg-info``
  15. directory, and metadata defined by `PEP 566`_ or its older specifications.
  16. By default, package metadata can live on the file system or in wheels on
  17. ``sys.path``. Through an extension mechanism, the metadata can live almost
  18. anywhere.
  19. Overview
  20. ========
  21. Let's say you wanted to get the version string for a package you've installed
  22. using ``pip``. We start by creating a virtual environment and installing
  23. something into it::
  24. $ python3 -m venv example
  25. $ source example/bin/activate
  26. (example) $ pip install importlib_metadata
  27. (example) $ pip install wheel
  28. You can get the version string for ``wheel`` by running the following::
  29. (example) $ python
  30. >>> from importlib_metadata import version
  31. >>> version('wheel')
  32. '0.32.3'
  33. You can also get the set of entry points keyed by group, such as
  34. ``console_scripts``, ``distutils.commands`` and others. Each group contains a
  35. sequence of :ref:`EntryPoint <entry-points>` objects.
  36. You can get the :ref:`metadata for a distribution <metadata>`::
  37. >>> list(metadata('wheel'))
  38. ['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']
  39. You can also get a :ref:`distribution's version number <version>`, list its
  40. :ref:`constituent files <files>`_, and get a list of the distribution's
  41. :ref:`requirements`_.
  42. Distributions
  43. =============
  44. .. CAUTION:: The ``Distribution`` class described here may or may not end up
  45. in the final stable public API. Consider this class `provisional
  46. <https://www.python.org/dev/peps/pep-0411/>`_ until the 1.0
  47. release.
  48. While the above API is the most common and convenient usage, you can get all
  49. of that information from the ``Distribution`` class. A ``Distribution`` is an
  50. abstract object that represents the metadata for a Python package. You can
  51. get the ``Distribution`` instance::
  52. >>> from importlib_metadata import distribution
  53. >>> dist = distribution('wheel')
  54. Thus, an alternative way to get the version number is through the
  55. ``Distribution`` instance::
  56. >>> dist.version
  57. '0.32.3'
  58. There are all kinds of additional metadata available on the ``Distribution``
  59. instance::
  60. >>> d.metadata['Requires-Python']
  61. '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
  62. >>> d.metadata['License']
  63. 'MIT'
  64. The full set of available metadata is not described here. See `PEP 566
  65. <https://www.python.org/dev/peps/pep-0566/>`_ for additional details.
  66. Functional API
  67. ==============
  68. This package provides the following functionality via its public API.
  69. .. _entry-points::
  70. Entry points
  71. ------------
  72. The ``entry_points()`` function returns a dictionary of all entry points,
  73. keyed by group. Entry points are represented by ``EntryPoint`` instances;
  74. each ``EntryPoint`` has a ``.name``, ``.group``, and ``.value`` attributes and
  75. a ``.load()`` method to resolve the value.
  76. >>> eps = entry_points()
  77. >>> list(eps)
  78. ['console_scripts', 'distutils.commands', 'distutils.setup_keywords', 'egg_info.writers', 'setuptools.installation']
  79. >>> scripts = eps['console_scripts']
  80. >>> wheel = [ep for ep in scripts if ep.name == 'wheel'][0]
  81. >>> wheel
  82. EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts')
  83. >>> main = wheel.load()
  84. >>> main
  85. <function main at 0x103528488>
  86. The ``group`` and ``name`` are arbitrary values defined by the package author
  87. and usually a client will wish to resolve all entry points for a particular
  88. group. Read `the setuptools docs
  89. <https://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins>`_
  90. for more information on entrypoints, their definition, and usage.
  91. .. _metadata::
  92. Distribution metadata
  93. ---------------------
  94. Every distribution includes some metadata, which you can extract using the
  95. ``metadata()`` function::
  96. >>> wheel_metadata = metadata('wheel')
  97. The keys of the returned data structure [#f1]_ name the metadata keywords, and
  98. their values are returned unparsed from the distribution metadata::
  99. >>> wheel_metadata['Requires-Python']
  100. '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
  101. .. _version::
  102. Distribution versions
  103. ---------------------
  104. The ``version()`` function is the quickest way to get a distribution's version
  105. number, as a string::
  106. >>> version('wheel')
  107. '0.32.3'
  108. .. _files::
  109. Distribution files
  110. ------------------
  111. You can also get the full set of files contained within a distribution. The
  112. ``files()`` function takes a distribution package name and returns all of the
  113. files installed by this distribution. Each file object returned is a
  114. ``PackagePath``, a `pathlib.Path`_ derived object with additional ``dist``,
  115. ``size``, and ``hash`` properties as indicated by the metadata. For example::
  116. >>> util = [p for p in files('wheel') if 'util.py' in str(p)][0]
  117. >>> util
  118. PackagePath('wheel/util.py')
  119. >>> util.size
  120. 859
  121. >>> util.dist
  122. <importlib_metadata._hooks.PathDistribution object at 0x101e0cef0>
  123. >>> util.hash
  124. <FileHash mode: sha256 value: bYkw5oMccfazVCoYQwKkkemoVyMAFoR34mmKBx8R1NI>
  125. Once you have the file, you can also read its contents::
  126. >>> print(util.read_text())
  127. import base64
  128. import sys
  129. ...
  130. def as_bytes(s):
  131. if isinstance(s, text_type):
  132. return s.encode('utf-8')
  133. return s
  134. .. _requirements::
  135. Distribution requirements
  136. -------------------------
  137. To get the full set of requirements for a distribution, use the ``requires()``
  138. function. Note that this returns an iterator::
  139. >>> list(requires('wheel'))
  140. ["pytest (>=3.0.0) ; extra == 'test'"]
  141. Extending the search algorithm
  142. ==============================
  143. Because package metadata is not available through ``sys.path`` searches, or
  144. package loaders directly, the metadata for a package is found through import
  145. system `finders`_. To find a distribution package's metadata,
  146. ``importlib_metadata`` queries the list of `meta path finders`_ on
  147. `sys.meta_path`_.
  148. By default ``importlib_metadata`` installs a finder for distribution packages
  149. found on the file system. This finder doesn't actually find any *packages*,
  150. but it can find the packages' metadata.
  151. The abstract class :py:class:`importlib.abc.MetaPathFinder` defines the
  152. interface expected of finders by Python's import system.
  153. ``importlib_metadata`` extends this protocol by looking for an optional
  154. ``find_distributions`` callable on the finders from
  155. ``sys.meta_path``. If the finder has this method, it must return
  156. an iterator over instances of the ``Distribution`` abstract class. This
  157. method must have the signature::
  158. def find_distributions(name=None, path=sys.path):
  159. """Return an iterable of all Distribution instances capable of
  160. loading the metadata for packages matching the name
  161. (or all names if not supplied) along the paths in the list
  162. of directories ``path`` (defaults to sys.path).
  163. """
  164. What this means in practice is that to support finding distribution package
  165. metadata in locations other than the file system, you should derive from
  166. ``Distribution`` and implement the ``load_metadata()`` method. This takes a
  167. single argument which is the name of the package whose metadata is being
  168. found. This instance of the ``Distribution`` base abstract class is what your
  169. finder's ``find_distributions()`` method should return.
  170. .. _`entry point API`: https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points
  171. .. _`metadata API`: https://setuptools.readthedocs.io/en/latest/pkg_resources.html#metadata-api
  172. .. _`Python 3.7 and newer`: https://docs.python.org/3/library/importlib.html#module-importlib.resources
  173. .. _`importlib_resources`: https://importlib-resources.readthedocs.io/en/latest/index.html
  174. .. _`PEP 566`: https://www.python.org/dev/peps/pep-0566/
  175. .. _`finders`: https://docs.python.org/3/reference/import.html#finders-and-loaders
  176. .. _`meta path finders`: https://docs.python.org/3/glossary.html#term-meta-path-finder
  177. .. _`sys.meta_path`: https://docs.python.org/3/library/sys.html#sys.meta_path
  178. .. _`pathlib.Path`: https://docs.python.org/3/library/pathlib.html#pathlib.Path
  179. .. rubric:: Footnotes
  180. .. [#f1] Technically, the returned distribution metadata object is an
  181. `email.message.Message
  182. <https://docs.python.org/3/library/email.message.html#email.message.EmailMessage>`_
  183. instance, but this is an implementation detail, and not part of the
  184. stable API. You should only use dictionary-like methods and syntax
  185. to access the metadata contents.