Skip to content

Commit da43812

Browse files
authored
Merge pull request #706 from jwodder/importlib-resource
Describe using importlib-metadata as an alternative to pkg_resources for single-sourcing versions
2 parents a66d18c + c12f847 commit da43812

1 file changed

Lines changed: 35 additions & 5 deletions

File tree

source/guides/single-sourcing-package-version.rst

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -75,17 +75,47 @@ number of your project:
7575
:file:`MANIFEST.in`).
7676

7777
#. Set the value in :file:`setup.py`, and have the project code use the
78-
``pkg_resources`` API.
78+
``importlib.metadata`` API to fetch the value at runtime.
79+
(``importlib.metadata`` was introduced in Python 3.8 and is available to
80+
older versions as the ``importlib-metadata`` project.) An installed
81+
project's version can be fetched with the API as follows::
7982

80-
::
83+
try:
84+
from importlib import metadata
85+
except ImportError:
86+
# Running on pre-3.8 Python; use importlib-metadata package
87+
import importlib_metadata as metadata
8188

82-
import pkg_resources
83-
assert pkg_resources.get_distribution('pip').version == '1.2.0'
89+
assert metadata.version('pip') == '1.2.0'
8490

85-
Be aware that the ``pkg_resources`` API only knows about what's in the
91+
Be aware that the ``importlib.metadata`` API only knows about what's in the
8692
installation metadata, which is not necessarily the code that's currently
8793
imported.
8894

95+
If a project uses this method to fetch its version at runtime, then its
96+
``install_requires`` value needs to be edited to install
97+
``importlib-metadata`` on pre-3.8 versions of Python like so::
98+
99+
setup(
100+
...
101+
install_requires=[
102+
...
103+
'importlib-metadata ~= 1.0 ; python_version < "3.8"',
104+
...
105+
],
106+
...
107+
)
108+
109+
An older (and less efficient) alternative to ``importlib.metadata`` is the
110+
``pkg_resources`` API provided by ``setuptools``::
111+
112+
import pkg_resources
113+
assert pkg_resources.get_distribution('pip').version == '1.2.0'
114+
115+
If a project uses ``pkg_resources`` to fetch its own version at runtime,
116+
then ``setuptools`` must be added to the project's ``install_requires``
117+
list.
118+
89119
Example using this technique: `setuptools <https://github.com/pypa/setuptools/blob/master/setuptools/version.py>`_.
90120

91121

0 commit comments

Comments
 (0)