Skip to content

Commit c6587af

Browse files
committed
More intelligently insert the pip path into sys.path
When inserting pip's library path into sys.path we do not want to override the stdlib. This is for several reasons: (1) The stdlib should only contain the stdlib. So there should not be other instances of pip there which will override our desired library. (2) If we were to override the stdlib and the path the pip library is installed in contains any libraries which override the stdlib (*cough*enum34*cough*) then we could break code which depends on the stdlib's APIs. Fixes #8214
1 parent 5cac4dc commit c6587af

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

news/8214.bugfix

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix installing packages which have a pyproject.toml when enum34 is installed.

src/pip/__main__.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import os
44
import sys
5+
import sysconfig
56

67
# Remove '' and current working directory from the first entry
78
# of sys.path, if present to avoid using current directory
@@ -13,12 +14,27 @@
1314
# If we are running from a wheel, add the wheel to sys.path
1415
# This allows the usage python pip-*.whl/pip install pip-*.whl
1516
if __package__ == '':
17+
# Retrieve the index in sys.path where all stdlib paths reside
18+
# (DESTSHARED is where some extension modules like math live).
19+
stdlib_path_indexes = []
20+
stdlib_paths = (sysconfig.get_path('stdlib'),
21+
sysconfig.get_path('platstdlib'),
22+
sysconfig.get_config_var('DESTSHARED'))
23+
for path in (p for p in stdlib_paths if p is not None):
24+
try:
25+
stdlib_path_indexes.append(sys.path.index(path))
26+
except ValueError:
27+
continue
28+
1629
# __file__ is pip-*.whl/pip/__main__.py
1730
# first dirname call strips of '/__main__.py', second strips off '/pip'
1831
# Resulting path is the name of the wheel itself
1932
# Add that to sys.path so we can import pip
20-
path = os.path.dirname(os.path.dirname(__file__))
21-
sys.path.insert(0, path)
33+
pip_installed_path = os.path.dirname(os.path.dirname(__file__))
34+
35+
# Insert this pip's library path directly after the stdlib so that
36+
# we import this pip's library even if another pip is installed.
37+
sys.path.insert(max(stdlib_path_indexes) + 1, pip_installed_path)
2238

2339
from pip._internal.cli.main import main as _main # isort:skip # noqa
2440

0 commit comments

Comments
 (0)