Debian Codegraph @

Doc/library/importlib.metadata.rst

raw
1 .. _using:
2
3 ========================================================
4 :mod:`!importlib.metadata` -- Accessing package metadata
5 ========================================================
6
7 .. module:: importlib.metadata
8 :synopsis: Accessing package metadata
9
10 .. versionadded:: 3.8
11 .. versionchanged:: 3.10
12 ``importlib.metadata`` is no longer provisional.
13
14 **Source code:** :source:`Lib/importlib/metadata/__init__.py`
15
16 ``importlib.metadata`` is a library that provides access to
17 the metadata of an installed `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_,
18 such as its entry points
19 or its top-level names (`Import Package <https://packaging.python.org/en/latest/glossary/#term-Import-Package>`_\s, modules, if any).
20 Built in part on Python's import system, this library
21 intends to replace similar functionality in the `entry point
22 API`_ and `metadata API`_ of ``pkg_resources``. Along with
23 :mod:`importlib.resources`,
24 this package can eliminate the need to use the older and less efficient
25 ``pkg_resources`` package.
26
27 ``importlib.metadata`` operates on third-party *distribution packages*
28 installed into Python's ``site-packages`` directory via tools such as
29 :pypi:`pip`.
30 Specifically, it works with distributions with discoverable
31 ``dist-info`` or ``egg-info`` directories,
32 and metadata defined by the `Core metadata specifications <https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata>`_.
33
34 .. important::
35
36 These are *not* necessarily equivalent to or correspond 1:1 with
37 the top-level *import package* names
38 that can be imported inside Python code.
39 One *distribution package* can contain multiple *import packages*
40 (and single modules),
41 and one top-level *import package*
42 may map to multiple *distribution packages*
43 if it is a namespace package.
44 You can use :ref:`packages_distributions() <package-distributions>`
45 to get a mapping between them.
46
47 By default, distribution metadata can live on the file system
48 or in zip archives on
49 :data:`sys.path`. Through an extension mechanism, the metadata can live almost
50 anywhere.
51
52
53 .. seealso::
54
55 https://importlib-metadata.readthedocs.io/
56 The documentation for ``importlib_metadata``, which supplies a
57 backport of ``importlib.metadata``.
58 This includes an `API reference
59 <https://importlib-metadata.readthedocs.io/en/latest/api.html>`__
60 for this module's classes and functions,
61 as well as a `migration guide
62 <https://importlib-metadata.readthedocs.io/en/latest/migration.html>`__
63 for existing users of ``pkg_resources``.
64
65
66 Overview
67 ========
68
69 Let's say you wanted to get the version string for a
70 `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_ you've installed
71 using ``pip``. We start by creating a virtual environment and installing
72 something into it:
73
74 .. code-block:: shell-session
75
76 $ python -m venv example
77 $ source example/bin/activate
78 (example) $ python -m pip install wheel
79
80 You can get the version string for ``wheel`` by running the following:
81
82 .. code-block:: pycon
83
84 (example) $ python
85 >>> from importlib.metadata import version # doctest: +SKIP
86 >>> version('wheel') # doctest: +SKIP
87 '0.32.3'
88
89 You can also get a collection of entry points selectable by properties of the EntryPoint (typically 'group' or 'name'), such as
90 ``console_scripts``, ``distutils.commands`` and others. Each group contains a
91 collection of :ref:`EntryPoint <entry-points>` objects.
92
93 You can get the :ref:`metadata for a distribution <metadata>`::
94
95 >>> list(metadata('wheel')) # doctest: +SKIP
96 ['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']
97
98 You can also get a :ref:`distribution's version number <version>`, list its
99 :ref:`constituent files <files>`, and get a list of the distribution's
100 :ref:`requirements`.
101
102
103 .. exception:: PackageNotFoundError
104
105 Subclass of :class:`ModuleNotFoundError` raised by several functions in this
106 module when queried for a distribution package which is not installed in the
107 current Python environment.
108
109
110 Functional API
111 ==============
112
113 This package provides the following functionality via its public API.
114
115
116 .. _entry-points:
117
118 Entry points
119 ------------
120
121 .. function:: entry_points(**select_params)
122
123 Returns a :class:`EntryPoints` instance describing entry points for the
124 current environment. Any given keyword parameters are passed to the
125 :meth:`!select` method for comparison to the attributes of
126 the individual entry point definitions.
127
128 Note: it is not currently possible to query for entry points based on
129 their :attr:`!EntryPoint.dist` attribute (as different :class:`!Distribution`
130 instances do not currently compare equal, even if they have the same attributes)
131
132 .. class:: EntryPoints
133
134 Details of a collection of installed entry points.
135
136 Also provides a ``.groups`` attribute that reports all identified entry
137 point groups, and a ``.names`` attribute that reports all identified entry
138 point names.
139
140 .. class:: EntryPoint
141
142 Details of an installed entry point.
143
144 Each :class:`!EntryPoint` instance has ``.name``, ``.group``, and ``.value``
145 attributes and a ``.load()`` method to resolve the value. There are also
146 ``.module``, ``.attr``, and ``.extras`` attributes for getting the
147 components of the ``.value`` attribute, and ``.dist`` for obtaining
148 information regarding the distribution package that provides the entry point.
149
150 Query all entry points::
151
152 >>> eps = entry_points() # doctest: +SKIP
153
154 The :func:`!entry_points` function returns a :class:`!EntryPoints` object,
155 a collection of all :class:`!EntryPoint` objects with ``names`` and ``groups``
156 attributes for convenience::
157
158 >>> sorted(eps.groups) # doctest: +SKIP
159 ['console_scripts', 'distutils.commands', 'distutils.setup_keywords', 'egg_info.writers', 'setuptools.installation']
160
161 :class:`!EntryPoints` has a :meth:`!select` method to select entry points
162 matching specific properties. Select entry points in the
163 ``console_scripts`` group::
164
165 >>> scripts = eps.select(group='console_scripts') # doctest: +SKIP
166
167 Equivalently, since :func:`!entry_points` passes keyword arguments
168 through to select::
169
170 >>> scripts = entry_points(group='console_scripts') # doctest: +SKIP
171
172 Pick out a specific script named "wheel" (found in the wheel project)::
173
174 >>> 'wheel' in scripts.names # doctest: +SKIP
175 True
176 >>> wheel = scripts['wheel'] # doctest: +SKIP
177
178 Equivalently, query for that entry point during selection::
179
180 >>> (wheel,) = entry_points(group='console_scripts', name='wheel') # doctest: +SKIP
181 >>> (wheel,) = entry_points().select(group='console_scripts', name='wheel') # doctest: +SKIP
182
183 Inspect the resolved entry point::
184
185 >>> wheel # doctest: +SKIP
186 EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts')
187 >>> wheel.module # doctest: +SKIP
188 'wheel.cli'
189 >>> wheel.attr # doctest: +SKIP
190 'main'
191 >>> wheel.extras # doctest: +SKIP
192 []
193 >>> main = wheel.load() # doctest: +SKIP
194 >>> main # doctest: +SKIP
195 <function main at 0x103528488>
196
197 The ``group`` and ``name`` are arbitrary values defined by the package author
198 and usually a client will wish to resolve all entry points for a particular
199 group. Read `the setuptools docs
200 <https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_
201 for more information on entry points, their definition, and usage.
202
203 .. versionchanged:: 3.12
204 The "selectable" entry points were introduced in ``importlib_metadata``
205 3.6 and Python 3.10. Prior to those changes, ``entry_points`` accepted
206 no parameters and always returned a dictionary of entry points, keyed
207 by group. With ``importlib_metadata`` 5.0 and Python 3.12,
208 ``entry_points`` always returns an ``EntryPoints`` object. See
209 :pypi:`backports.entry_points_selectable`
210 for compatibility options.
211
212 .. versionchanged:: 3.13
213 ``EntryPoint`` objects no longer present a tuple-like interface
214 (:meth:`~object.__getitem__`).
215
216 .. _metadata:
217
218 Distribution metadata
219 ---------------------
220
221 .. function:: metadata(distribution_name)
222
223 Return the distribution metadata corresponding to the named
224 distribution package as a :class:`PackageMetadata` instance.
225
226 Raises :exc:`PackageNotFoundError` if the named distribution
227 package is not installed in the current Python environment.
228
229 .. class:: PackageMetadata
230
231 A concrete implementation of the
232 `PackageMetadata protocol <https://importlib-metadata.readthedocs.io/en/latest/api.html#importlib_metadata.PackageMetadata>`_.
233
234 In addition to providing the defined protocol methods and attributes, subscripting
235 the instance is equivalent to calling the :meth:`!get` method.
236
237 Every `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_
238 includes some metadata, which you can extract using the :func:`!metadata` function::
239
240 >>> wheel_metadata = metadata('wheel') # doctest: +SKIP
241
242 The keys of the returned data structure name the metadata keywords, and
243 the values are returned unparsed from the distribution metadata::
244
245 >>> wheel_metadata['Requires-Python'] # doctest: +SKIP
246 '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
247
248 :class:`PackageMetadata` also presents a :attr:`!json` attribute that returns
249 all the metadata in a JSON-compatible form per :PEP:`566`::
250
251 >>> wheel_metadata.json['requires_python']
252 '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
253
254 The full set of available metadata is not described here.
255 See the PyPA `Core metadata specification <https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata>`_ for additional details.
256
257 .. versionchanged:: 3.10
258 The ``Description`` is now included in the metadata when presented
259 through the payload. Line continuation characters have been removed.
260
261 The ``json`` attribute was added.
262
263
264 .. _version:
265
266 Distribution versions
267 ---------------------
268
269 .. function:: version(distribution_name)
270
271 Return the installed distribution package
272 `version <https://packaging.python.org/en/latest/specifications/core-metadata/#version>`__
273 for the named distribution package.
274
275 Raises :exc:`PackageNotFoundError` if the named distribution
276 package is not installed in the current Python environment.
277
278 The :func:`!version` function is the quickest way to get a
279 `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_'s version
280 number, as a string::
281
282 >>> version('wheel') # doctest: +SKIP
283 '0.32.3'
284
285
286 .. _files:
287
288 Distribution files
289 ------------------
290
291 .. function:: files(distribution_name)
292
293 Return the full set of files contained within the named
294 distribution package.
295
296 Raises :exc:`PackageNotFoundError` if the named distribution
297 package is not installed in the current Python environment.
298
299 Returns :const:`None` if the distribution is found but the installation
300 database records reporting the files associated with the distribuion package
301 are missing.
302
303 .. class:: PackagePath
304
305 A :class:`pathlib.PurePath` derived object with additional ``dist``,
306 ``size``, and ``hash`` properties corresponding to the distribution
307 package's installation metadata for that file.
308
309 The :func:`!files` function takes a
310 `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_
311 name and returns all of the files installed by this distribution. Each file is reported
312 as a :class:`PackagePath` instance. For example::
313
314 >>> util = [p for p in files('wheel') if 'util.py' in str(p)][0] # doctest: +SKIP
315 >>> util # doctest: +SKIP
316 PackagePath('wheel/util.py')
317 >>> util.size # doctest: +SKIP
318 859
319 >>> util.dist # doctest: +SKIP
320 <importlib.metadata._hooks.PathDistribution object at 0x101e0cef0>
321 >>> util.hash # doctest: +SKIP
322 <FileHash mode: sha256 value: bYkw5oMccfazVCoYQwKkkemoVyMAFoR34mmKBx8R1NI>
323
324 Once you have the file, you can also read its contents::
325
326 >>> print(util.read_text()) # doctest: +SKIP
327 import base64
328 import sys
329 ...
330 def as_bytes(s):
331 if isinstance(s, text_type):
332 return s.encode('utf-8')
333 return s
334
335 You can also use the :meth:`!locate` method to get the absolute
336 path to the file::
337
338 >>> util.locate() # doctest: +SKIP
339 PosixPath('/home/gustav/example/lib/site-packages/wheel/util.py')
340
341 In the case where the metadata file listing files
342 (``RECORD`` or ``SOURCES.txt``) is missing, :func:`!files` will
343 return :const:`None`. The caller may wish to wrap calls to
344 :func:`!files` in `always_iterable
345 <https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable>`_
346 or otherwise guard against this condition if the target
347 distribution is not known to have the metadata present.
348
349 .. _requirements:
350
351 Distribution requirements
352 -------------------------
353
354 .. function:: requires(distribution_name)
355
356 Return the declared dependency specifiers for the named
357 distribution package.
358
359 Raises :exc:`PackageNotFoundError` if the named distribution
360 package is not installed in the current Python environment.
361
362 To get the full set of requirements for a `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_,
363 use the :func:`!requires`
364 function::
365
366 >>> requires('wheel') # doctest: +SKIP
367 ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"]
368
369
370 .. _package-distributions:
371 .. _import-distribution-package-mapping:
372
373 Mapping import to distribution packages
374 ---------------------------------------
375
376 .. function:: packages_distributions()
377
378 Return a mapping from the top level module and import package
379 names found via :data:`sys.meta_path` to the names of the distribution
380 packages (if any) that provide the corresponding files.
381
382 To allow for namespace packages (which may have members provided by
383 multiple distribution packages), each top level import name maps to a
384 list of distribution names rather than mapping directly to a single name.
385
386 A convenience method to resolve the `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_
387 name (or names, in the case of a namespace package)
388 that provide each importable top-level
389 Python module or `Import Package <https://packaging.python.org/en/latest/glossary/#term-Import-Package>`_::
390
391 >>> packages_distributions()
392 {'importlib_metadata': ['importlib-metadata'], 'yaml': ['PyYAML'], 'jaraco': ['jaraco.classes', 'jaraco.functools'], ...}
393
394 Some editable installs, `do not supply top-level names
395 <https://github.com/pypa/packaging-problems/issues/609>`_, and thus this
396 function is not reliable with such installs.
397
398 .. versionadded:: 3.10
399
400 .. _distributions:
401
402 Distributions
403 =============
404
405 .. function:: distribution(distribution_name)
406
407 Return a :class:`Distribution` instance describing the named
408 distribution package.
409
410 Raises :exc:`PackageNotFoundError` if the named distribution
411 package is not installed in the current Python environment.
412
413 .. class:: Distribution
414
415 Details of an installed distribution package.
416
417 Note: different :class:`!Distribution` instances do not currently compare
418 equal, even if they relate to the same installed distribution and
419 accordingly have the same attributes.
420
421 While the module level API described above is the most common and convenient usage,
422 you can get all of that information from the :class:`!Distribution` class.
423 :class:`!Distribution` is an abstract object that represents the metadata for
424 a Python `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_.
425 You can get the concrete :class:`!Distribution` subclass instance for an installed
426 distribution package by calling the :func:`distribution` function::
427
428 >>> from importlib.metadata import distribution # doctest: +SKIP
429 >>> dist = distribution('wheel') # doctest: +SKIP
430 >>> type(dist) # doctest: +SKIP
431 <class 'importlib.metadata.PathDistribution'>
432
433 Thus, an alternative way to get the version number is through the
434 :class:`!Distribution` instance::
435
436 >>> dist.version # doctest: +SKIP
437 '0.32.3'
438
439 There are all kinds of additional metadata available on :class:`!Distribution`
440 instances::
441
442 >>> dist.metadata['Requires-Python'] # doctest: +SKIP
443 '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
444 >>> dist.metadata['License'] # doctest: +SKIP
445 'MIT'
446
447 For editable packages, an ``origin`` property may present :pep:`610`
448 metadata::
449
450 >>> dist.origin.url
451 'file:///path/to/wheel-0.32.3.editable-py3-none-any.whl'
452
453 The full set of available metadata is not described here.
454 See the PyPA `Core metadata specification <https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata>`_ for additional details.
455
456 .. versionadded:: 3.13
457 The ``.origin`` property was added.
458
459 Distribution Discovery
460 ======================
461
462 By default, this package provides built-in support for discovery of metadata
463 for file system and zip file `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_\s.
464 This metadata finder search defaults to ``sys.path``, but varies slightly in how it interprets those values from how other import machinery does. In particular:
465
466 - ``importlib.metadata`` does not honor :class:`bytes` objects on ``sys.path``.
467 - ``importlib.metadata`` will incidentally honor :py:class:`pathlib.Path` objects on ``sys.path`` even though such values will be ignored for imports.
468
469
470 Extending the search algorithm
471 ==============================
472
473 Because `Distribution Package <https://packaging.python.org/en/latest/glossary/#term-Distribution-Package>`_ metadata
474 is not available through :data:`sys.path` searches, or
475 package loaders directly,
476 the metadata for a distribution is found through import
477 system :ref:`finders <finders-and-loaders>`. To find a distribution package's metadata,
478 ``importlib.metadata`` queries the list of :term:`meta path finders <meta path finder>` on
479 :data:`sys.meta_path`.
480
481 By default ``importlib.metadata`` installs a finder for distribution packages
482 found on the file system.
483 This finder doesn't actually find any *distributions*,
484 but it can find their metadata.
485
486 The abstract class :py:class:`importlib.abc.MetaPathFinder` defines the
487 interface expected of finders by Python's import system.
488 ``importlib.metadata`` extends this protocol by looking for an optional
489 ``find_distributions`` callable on the finders from
490 :data:`sys.meta_path` and presents this extended interface as the
491 ``DistributionFinder`` abstract base class, which defines this abstract
492 method::
493
494 @abc.abstractmethod
495 def find_distributions(context=DistributionFinder.Context()):
496 """Return an iterable of all Distribution instances capable of
497 loading the metadata for packages for the indicated ``context``.
498 """
499
500 The ``DistributionFinder.Context`` object provides ``.path`` and ``.name``
501 properties indicating the path to search and name to match and may
502 supply other relevant context.
503
504 What this means in practice is that to support finding distribution package
505 metadata in locations other than the file system, subclass
506 ``Distribution`` and implement the abstract methods. Then from
507 a custom finder, return instances of this derived ``Distribution`` in the
508 ``find_distributions()`` method.
509
510 Example
511 -------
512
513 Consider for example a custom finder that loads Python
514 modules from a database::
515
516 class DatabaseImporter(importlib.abc.MetaPathFinder):
517 def __init__(self, db):
518 self.db = db
519
520 def find_spec(self, fullname, target=None) -> ModuleSpec:
521 return self.db.spec_from_name(fullname)
522
523 sys.meta_path.append(DatabaseImporter(connect_db(...)))
524
525 That importer now presumably provides importable modules from a
526 database, but it provides no metadata or entry points. For this
527 custom importer to provide metadata, it would also need to implement
528 ``DistributionFinder``::
529
530 from importlib.metadata import DistributionFinder
531
532 class DatabaseImporter(DistributionFinder):
533 ...
534
535 def find_distributions(self, context=DistributionFinder.Context()):
536 query = dict(name=context.name) if context.name else {}
537 for dist_record in self.db.query_distributions(query):
538 yield DatabaseDistribution(dist_record)
539
540 In this way, ``query_distributions`` would return records for
541 each distribution served by the database matching the query. For
542 example, if ``requests-1.0`` is in the database, ``find_distributions``
543 would yield a ``DatabaseDistribution`` for ``Context(name='requests')``
544 or ``Context(name=None)``.
545
546 For the sake of simplicity, this example ignores ``context.path``\. The
547 ``path`` attribute defaults to ``sys.path`` and is the set of import paths to
548 be considered in the search. A ``DatabaseImporter`` could potentially function
549 without any concern for a search path. Assuming the importer does no
550 partitioning, the "path" would be irrelevant. In order to illustrate the
551 purpose of ``path``, the example would need to illustrate a more complex
552 ``DatabaseImporter`` whose behavior varied depending on
553 ``sys.path``/``PYTHONPATH``. In that case, the ``find_distributions`` should
554 honor the ``context.path`` and only yield ``Distribution``\ s pertinent to that
555 path.
556
557 ``DatabaseDistribution``, then, would look something like::
558
559 class DatabaseDistribution(importlib.metadata.Distribution):
560 def __init__(self, record):
561 self.record = record
562
563 def read_text(self, filename):
564 """
565 Read a file like "METADATA" for the current distribution.
566 """
567 if filename == "METADATA":
568 return f"""Name: {self.record.name}
569 Version: {self.record.version}
570 """
571 if filename == "entry_points.txt":
572 return "\n".join(
573 f"""[{ep.group}]\n{ep.name}={ep.value}"""
574 for ep in self.record.entry_points)
575
576 def locate_file(self, path):
577 raise RuntimeError("This distribution has no file system")
578
579 This basic implementation should provide metadata and entry points for
580 packages served by the ``DatabaseImporter``, assuming that the
581 ``record`` supplies suitable ``.name``, ``.version``, and
582 ``.entry_points`` attributes.
583
584 The ``DatabaseDistribution`` may also provide other metadata files, like
585 ``RECORD`` (required for ``Distribution.files``) or override the
586 implementation of ``Distribution.files``. See the source for more inspiration.
587
588
589 .. _`entry point API`: https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points
590 .. _`metadata API`: https://setuptools.readthedocs.io/en/latest/pkg_resources.html#metadata-api