gh-146369: Ensure PYTHON_LAZY_IMPORTS=none overrides __lazy_modules__ (#146371)

This commit is contained in:
Hugo van Kemenade 2026-03-25 13:08:45 +02:00 committed by GitHub
parent 2be147e1e7
commit d0e66ef1c0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 46 additions and 1 deletions

View file

@ -1088,6 +1088,49 @@ def test_env_var_lazy_imports_none_disables_all_lazy(self):
self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
self.assertIn("EAGER", result.stdout)
def test_cli_lazy_imports_none_disables_dunder_lazy_modules(self):
"""-X lazy_imports=none should override __lazy_modules__."""
code = textwrap.dedent("""
import sys
__lazy_modules__ = ["json"]
import json
if 'json' in sys.modules:
print("EAGER")
else:
print("LAZY")
""")
result = subprocess.run(
[sys.executable, "-X", "lazy_imports=none", "-c", code],
capture_output=True,
text=True,
)
self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
self.assertIn("EAGER", result.stdout)
def test_env_var_lazy_imports_none_disables_dunder_lazy_modules(self):
"""PYTHON_LAZY_IMPORTS=none should override __lazy_modules__."""
code = textwrap.dedent("""
import sys
__lazy_modules__ = ["json"]
import json
if 'json' in sys.modules:
print("EAGER")
else:
print("LAZY")
""")
import os
env = os.environ.copy()
env["PYTHON_LAZY_IMPORTS"] = "none"
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True,
env=env,
)
self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
self.assertIn("EAGER", result.stdout)
def test_cli_overrides_env_var(self):
"""Command-line option should take precedence over environment variable."""
# PEP 810: -X lazy_imports takes precedence over PYTHON_LAZY_IMPORTS

View file

@ -0,0 +1,2 @@
Ensure ``-X lazy_imports=none``` and ``PYTHON_LAZY_IMPORTS=none``` override
``__lazy_modules__``. Patch by Hugo van Kemenade.

View file

@ -3086,7 +3086,7 @@ _PyEval_LazyImportName(PyThreadState *tstate, PyObject *builtins,
break;
}
if (!lazy) {
if (!lazy && PyImport_GetLazyImportsMode() != PyImport_LAZY_NONE) {
// See if __lazy_modules__ forces this to be lazy.
lazy = check_lazy_import_compatibility(tstate, globals, name, level);
if (lazy < 0) {