Skip to content

Commit fb01b18

Browse files
committed
Warn on unexpected imports during install
1 parent 768810e commit fb01b18

5 files changed

Lines changed: 183 additions & 4 deletions

File tree

‎news/13912.feature.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Emit a deprecation warning when pip imports an unexpected module after
2+
installation of a distribution has started.

‎src/pip/_internal/commands/install.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
import os
77
import shutil
88
import site
9+
import sys
910
from optparse import SUPPRESS_HELP, Values
1011
from pathlib import Path
12+
from typing import Any
1113

1214
from pip._vendor.packaging.utils import canonicalize_name
1315
from pip._vendor.requests.exceptions import InvalidProxyURL
@@ -43,6 +45,7 @@
4345
InstallRequirement,
4446
)
4547
from pip._internal.utils.compat import WINDOWS
48+
from pip._internal.utils.deprecation import deprecated
4649
from pip._internal.utils.filesystem import test_writable_dir
4750
from pip._internal.utils.logging import getLogger
4851
from pip._internal.utils.misc import (
@@ -63,6 +66,70 @@
6366
logger = getLogger(__name__)
6467

6568

69+
_IMPORT_AUDIT_HOOK_INSTALLED = False
70+
_MISSING_MODULES: set[str] = set()
71+
72+
# Non-stdlib modules pip (or its vendored dependencies) may import lazily
73+
# after installation has started. Importing them eagerly keeps the audit
74+
# hook from misattributing them to a freshly installed distribution.
75+
_EAGER_IMPORTS: tuple[str, ...] = (
76+
# Used by rich when emitting output to a legacy Windows console.
77+
"pip._vendor.rich._windows_renderer",
78+
# Optional stub that packaging imports while probing manylinux support.
79+
"_manylinux",
80+
)
81+
82+
83+
# Imports of standard library modules are always safe: they cannot be
84+
# shadowed by a distribution pip has just installed.
85+
_STDLIB_MODULE_NAMES: frozenset[str] = frozenset(sys.stdlib_module_names) | frozenset(
86+
sys.builtin_module_names
87+
)
88+
89+
90+
def _prevent_import_hook(name: str, args: tuple[Any, ...]) -> None:
91+
if name != "import":
92+
return
93+
module = args[0]
94+
if module in _MISSING_MODULES:
95+
raise ImportError(f"No module named {module!r}")
96+
if module.partition(".")[0] in _STDLIB_MODULE_NAMES:
97+
return
98+
deprecated(
99+
reason=f"Unexpected import of {module!r} after pip install started.",
100+
replacement=None,
101+
gone_in="26.3",
102+
issue=13842,
103+
include_source=True,
104+
stacklevel=3,
105+
)
106+
107+
108+
def _eagerly_import_modules() -> None:
109+
"""Import modules pip uses lazily so the audit hook ignores them later."""
110+
for module in _EAGER_IMPORTS:
111+
try:
112+
__import__(module)
113+
except ImportError:
114+
# Record the module as missing so the hook can raise ImportError
115+
# instead of trying to import it again.
116+
_MISSING_MODULES.add(module)
117+
118+
119+
def _prevent_further_imports() -> None:
120+
"""Install an audit hook that warns on unexpected imports after pip install starts.
121+
122+
Eagerly pre-imports the known lazy imports first so the hook only fires
123+
on genuinely unexpected modules.
124+
"""
125+
global _IMPORT_AUDIT_HOOK_INSTALLED
126+
if _IMPORT_AUDIT_HOOK_INSTALLED:
127+
return
128+
129+
_IMPORT_AUDIT_HOOK_INSTALLED = True
130+
sys.addaudithook(_prevent_import_hook)
131+
132+
66133
class InstallCommand(RequirementCommand):
67134
"""
68135
Install packages from:
@@ -459,6 +526,13 @@ def run(self, options: Values, args: list[str]) -> int:
459526
if options.target_dir or options.prefix_path:
460527
warn_script_location = False
461528

529+
# Warn on late imports so we don't silently pick up a module
530+
# from a distribution pip is about to install.
531+
try:
532+
_eagerly_import_modules()
533+
finally:
534+
_prevent_further_imports()
535+
462536
installed = install_given_reqs(
463537
to_install,
464538
root=options.root_path,

‎src/pip/_internal/utils/deprecation.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717

1818
class PipDeprecationWarning(Warning):
19-
pass
19+
include_source: bool = False
2020

2121

2222
_original_showwarning: Any = None
@@ -38,7 +38,10 @@ def _showwarning(
3838
# We use a specially named logger which will handle all of the
3939
# deprecation messages for pip.
4040
logger = logging.getLogger("pip._internal.deprecations")
41-
logger.warning(message)
41+
if isinstance(message, PipDeprecationWarning) and message.include_source:
42+
logger.warning("%s (%s:%s)", message, filename, lineno)
43+
else:
44+
logger.warning(message)
4245
else:
4346
_original_showwarning(message, category, filename, lineno, file, line)
4447

@@ -61,6 +64,8 @@ def deprecated(
6164
gone_in: str | None,
6265
feature_flag: str | None = None,
6366
issue: int | None = None,
67+
stacklevel: int = 2,
68+
include_source: bool = False,
6469
) -> None:
6570
"""Helper to deprecate existing functionality.
6671
@@ -80,6 +85,12 @@ def deprecated(
8085
issue:
8186
Issue number on the tracker that would serve as a useful place for
8287
users to find related discussion and provide feedback.
88+
stacklevel:
89+
How many frames up the call stack to attribute the warning to.
90+
Defaults to 2 (the caller of deprecated()).
91+
include_source:
92+
If True, include the source filename and line number in the warning
93+
output. Useful when the warning originates from external code.
8394
"""
8495

8596
# Determine whether or not the feature is already gone in this version.
@@ -123,4 +134,6 @@ def deprecated(
123134
if is_gone:
124135
raise PipDeprecationWarning(message)
125136

126-
warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
137+
warning = PipDeprecationWarning(message)
138+
warning.include_source = include_source
139+
warnings.warn(warning, stacklevel=stacklevel)

‎tests/functional/test_install.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,57 @@ def test_pip_second_command_line_interface_works(
310310
result.did_create(initools_folder)
311311

312312

313+
def test_install_warns_on_unexpected_post_install_import(
314+
script: PipTestEnvironment,
315+
) -> None:
316+
"""
317+
Verify that pip warns when an unexpected import happens after the
318+
install audit hook has been registered. The hook is installed before
319+
``install_given_reqs`` runs, so imports issued from code running after
320+
that point must trigger the deprecation warning.
321+
"""
322+
wheel_path = create_basic_wheel_for_package(script, "mypackage", "1.0")
323+
runner = script.scratch_path / "run_install.py"
324+
runner.write_text(
325+
textwrap.dedent(
326+
"""\
327+
import sys
328+
import pip._internal.commands.install as _install_mod
329+
_orig_get_environment = _install_mod.get_environment
330+
331+
def _patched_get_environment(lib_locations):
332+
try:
333+
import pip_unexpected_module_xyz
334+
except ModuleNotFoundError:
335+
pass
336+
return _orig_get_environment(lib_locations)
337+
338+
_install_mod.get_environment = _patched_get_environment
339+
340+
from pip._internal.cli.main import main
341+
wheels_dir = sys.argv[1]
342+
sys.exit(main([
343+
"install",
344+
"--no-index",
345+
"--find-links",
346+
wheels_dir,
347+
"mypackage"
348+
])
349+
)
350+
"""
351+
)
352+
)
353+
354+
result = script.run(
355+
"python", str(runner), str(wheel_path.parent), expect_stderr=True
356+
)
357+
assert (
358+
"Unexpected import of 'pip_unexpected_module_xyz' "
359+
"after pip install started" in result.stderr
360+
)
361+
assert "run_install.py:7)" in result.stderr
362+
363+
313364
def test_install_exit_status_code_when_no_requirements(
314365
script: PipTestEnvironment,
315366
) -> None:

‎tests/unit/test_command_install.py‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
import errno
22
import sys
3+
import warnings
34
from unittest import mock
45

56
import pytest
67

78
from pip._vendor.requests.exceptions import InvalidProxyURL
89

910
from pip._internal.commands import install
10-
from pip._internal.commands.install import create_os_error_message, decide_user_install
11+
from pip._internal.commands.install import (
12+
_prevent_further_imports,
13+
create_os_error_message,
14+
decide_user_install,
15+
)
16+
from pip._internal.utils.deprecation import PipDeprecationWarning
1117

1218

1319
class TestDecideUserInstall:
@@ -183,3 +189,36 @@ def test_create_os_error_message(
183189
monkeypatch.setattr(install, "running_under_virtualenv", lambda: False)
184190
msg = create_os_error_message(error, show_traceback, using_user_site)
185191
assert msg == expected
192+
193+
194+
def test_prevent_further_imports_warns_on_import() -> None:
195+
"""
196+
An import issued after _prevent_further_imports() has run must emit a
197+
deprecation warning via the registered audit hook, except when the
198+
imported module lives in the standard library.
199+
"""
200+
captured_hooks: list[mock.Mock] = []
201+
202+
with mock.patch.object(install, "_IMPORT_AUDIT_HOOK_INSTALLED", False):
203+
with mock.patch.object(sys, "addaudithook", side_effect=captured_hooks.append):
204+
_prevent_further_imports()
205+
206+
assert len(captured_hooks) == 1, "Expected exactly one audit hook to be registered"
207+
audit_hook = captured_hooks[0]
208+
209+
with warnings.catch_warnings(record=True) as caught:
210+
warnings.simplefilter("always")
211+
audit_hook("import", ("unknown_module",))
212+
213+
assert len(caught) == 1
214+
assert "unknown_module" in str(caught[0].message)
215+
assert issubclass(caught[0].category, PipDeprecationWarning)
216+
217+
# Standard library imports must not emit a warning: pip cannot shadow
218+
# them with a freshly installed distribution.
219+
with warnings.catch_warnings(record=True) as caught:
220+
warnings.simplefilter("always")
221+
audit_hook("import", ("os",))
222+
audit_hook("import", ("encodings.iso8859_15",))
223+
224+
assert caught == []

0 commit comments

Comments
 (0)