|
| 1 | +import contextlib |
1 | 2 | import functools
|
2 | 3 | import os
|
| 4 | +import sys |
3 | 5 | from typing import TYPE_CHECKING, List, Optional, Type, cast
|
4 | 6 |
|
| 7 | +from pip._internal.utils.misc import strtobool |
| 8 | + |
5 | 9 | from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
|
6 | 10 |
|
7 | 11 | if TYPE_CHECKING:
|
|
22 | 26 | ]
|
23 | 27 |
|
24 | 28 |
|
| 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 | + import importlib.metadata |
| 48 | + |
| 49 | + return bool(getattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA", True)) |
| 50 | + |
| 51 | + |
25 | 52 | class Backend(Protocol):
|
26 | 53 | Distribution: Type[BaseDistribution]
|
27 | 54 | Environment: Type[BaseEnvironment]
|
28 | 55 |
|
29 | 56 |
|
30 | 57 | @functools.lru_cache(maxsize=None)
|
31 | 58 | def select_backend() -> Backend:
|
32 |
| - if os.environ.get("_PIP_METADATA_BACKEND_IMPORTLIB"): |
| 59 | + if _should_use_importlib_metadata(): |
33 | 60 | from . import importlib
|
34 | 61 |
|
35 | 62 | return cast(Backend, importlib)
|
|
0 commit comments