Skip to content

Commit

Permalink
Enable importlib.metadata backend on Python 3.11
Browse files Browse the repository at this point in the history
  • Loading branch information
uranusjr committed Apr 19, 2022
1 parent c247ddc commit a1986d9
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/pip/_internal/metadata/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import contextlib
import functools
import os
import sys
from typing import TYPE_CHECKING, List, Optional, Type, cast

from pip._internal.utils.misc import strtobool

from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel

if TYPE_CHECKING:
Expand All @@ -22,14 +26,39 @@
]


def _should_use_importlib_metadata() -> bool:
"""Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend.
By default, pip uses ``importlib.metadata`` on Python 3.11+, and
``pkg_resourcess`` otherwise. This can be overriden by a couple of ways:
* If environment variable ``_PIP_USE_IMPORTLIB_METADATA`` is set, it
dictates whether ``importlib.metadata`` is used, regardless of Python
version.
* On Python 3.11+, Python distributors can patch ``importlib.metadata``
to add a global constant ``_PIP_USE_IMPORTLIB_METADATA = False``. This
makes pip use ``pkg_resources`` (unless the user set the aforementioned
environment variable to *True*).
"""
with contextlib.suppress(KeyError, ValueError):
return bool(strtobool(os.environ["_PIP_USE_IMPORTLIB_METADATA"]))
if sys.version_info < (3, 11):
return False
try:
import importlib.metadata
except ImportError:
return True
return bool(getattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA", True))


class Backend(Protocol):
Distribution: Type[BaseDistribution]
Environment: Type[BaseEnvironment]


@functools.lru_cache(maxsize=None)
def select_backend() -> Backend:
if os.environ.get("_PIP_METADATA_BACKEND_IMPORTLIB"):
if _should_use_importlib_metadata():
from . import importlib

return cast(Backend, importlib)
Expand Down

0 comments on commit a1986d9

Please sign in to comment.