Skip to content

Commit a1986d9

Browse files
committed
Enable importlib.metadata backend on Python 3.11
1 parent c247ddc commit a1986d9

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

src/pip/_internal/metadata/__init__.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
1+
import contextlib
12
import functools
23
import os
4+
import sys
35
from typing import TYPE_CHECKING, List, Optional, Type, cast
46

7+
from pip._internal.utils.misc import strtobool
8+
59
from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
610

711
if TYPE_CHECKING:
@@ -22,14 +26,39 @@
2226
]
2327

2428

29+
def _should_use_importlib_metadata() -> bool:
30+
"""Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend.
31+
32+
By default, pip uses ``importlib.metadata`` on Python 3.11+, and
33+
``pkg_resourcess`` otherwise. This can be overriden by a couple of ways:
34+
35+
* If environment variable ``_PIP_USE_IMPORTLIB_METADATA`` is set, it
36+
dictates whether ``importlib.metadata`` is used, regardless of Python
37+
version.
38+
* On Python 3.11+, Python distributors can patch ``importlib.metadata``
39+
to add a global constant ``_PIP_USE_IMPORTLIB_METADATA = False``. This
40+
makes pip use ``pkg_resources`` (unless the user set the aforementioned
41+
environment variable to *True*).
42+
"""
43+
with contextlib.suppress(KeyError, ValueError):
44+
return bool(strtobool(os.environ["_PIP_USE_IMPORTLIB_METADATA"]))
45+
if sys.version_info < (3, 11):
46+
return False
47+
try:
48+
import importlib.metadata
49+
except ImportError:
50+
return True
51+
return bool(getattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA", True))
52+
53+
2554
class Backend(Protocol):
2655
Distribution: Type[BaseDistribution]
2756
Environment: Type[BaseEnvironment]
2857

2958

3059
@functools.lru_cache(maxsize=None)
3160
def select_backend() -> Backend:
32-
if os.environ.get("_PIP_METADATA_BACKEND_IMPORTLIB"):
61+
if _should_use_importlib_metadata():
3362
from . import importlib
3463

3564
return cast(Backend, importlib)

0 commit comments

Comments
 (0)