File size: 19,423 Bytes
a4edccc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | diff --git a/Lib/test/test_import/test_pep810_lazy_imports_aug.py b/Lib/test/test_import/test_pep810_lazy_imports_aug.py
new file mode 100644
index 00000000..00000000
--- /dev/null
+++ b/Lib/test/test_import/test_pep810_lazy_imports_aug.py
@@ -0,0 +1,380 @@
+"""Augmented F2P tests for PEP 810 explicit lazy imports."""
+
+import dis
+import io
+import importlib
+import os
+import pathlib
+import subprocess
+import sys
+import tempfile
+import textwrap
+import traceback
+import types
+import unittest
+
+
+class LazyImportAugmentedTests(unittest.TestCase):
+ def tearDown(self):
+ for name in list(sys.modules):
+ if name.startswith("pep810_aug_"):
+ del sys.modules[name]
+ if hasattr(sys, "set_lazy_imports_filter"):
+ sys.set_lazy_imports_filter(None)
+ if hasattr(sys, "set_lazy_imports"):
+ sys.set_lazy_imports("normal")
+ if hasattr(sys, "lazy_modules"):
+ sys.lazy_modules.clear()
+
+ def make_module(self, directory, name, body):
+ path = pathlib.Path(directory)
+ parts = name.split(".")
+ for i in range(1, len(parts)):
+ pkg = path.joinpath(*parts[:i])
+ pkg.mkdir(exist_ok=True)
+ init = pkg / "__init__.py"
+ init.touch()
+ mod = path.joinpath(*parts)
+ mod.parent.mkdir(parents=True, exist_ok=True)
+ mod.with_suffix(".py").write_text(textwrap.dedent(body), encoding="utf-8")
+
+ def exec_with_path(self, directory, source):
+ sys.path.insert(0, directory)
+ self.addCleanup(lambda: sys.path.remove(directory) if directory in sys.path else None)
+ namespace = {"__name__": "pep810_aug_driver", "__file__": os.path.join(directory, "driver.py")}
+ exec(textwrap.dedent(source), namespace)
+ return namespace
+
+ def test_explicit_lazy_import_reifies_only_on_attribute_access(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ marker = os.path.join(tmp, "side_effect")
+ self.make_module(tmp, "pep810_aug_side_effect", f"""
+ import pathlib
+ pathlib.Path({marker!r}).write_text("imported", encoding="utf-8")
+ VALUE = 42
+ """)
+
+ namespace = self.exec_with_path(tmp, "lazy import pep810_aug_side_effect")
+ proxy = namespace["pep810_aug_side_effect"]
+
+ self.assertIsInstance(proxy, types.LazyImportType)
+ self.assertNotIn("pep810_aug_side_effect", sys.modules)
+ self.assertFalse(os.path.exists(marker))
+ resolved = proxy.resolve()
+ self.assertEqual(resolved.VALUE, 42)
+ self.assertTrue(os.path.exists(marker))
+ self.assertIn("pep810_aug_side_effect", sys.modules)
+
+ def test_lazy_from_import_reifies_accessed_name_only(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_aug_values", """
+ FIRST = "first"
+ SECOND = "second"
+ """)
+
+ namespace = self.exec_with_path(
+ tmp,
+ "lazy from pep810_aug_values import FIRST, SECOND",
+ )
+ first = namespace["FIRST"]
+ second = namespace["SECOND"]
+
+ self.assertIsInstance(first, types.LazyImportType)
+ self.assertIsInstance(second, types.LazyImportType)
+ self.assertEqual(first.resolve(), "first")
+ self.assertIsInstance(namespace["SECOND"], types.LazyImportType)
+ self.assertEqual(namespace["SECOND"].resolve(), "second")
+
+ def test_global_all_and_none_modes_override_regular_and_lazy_imports(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_aug_global_lazy", "FLAG = 'lazy'")
+ self.make_module(tmp, "pep810_aug_global_eager", "FLAG = 'eager'")
+
+ sys.set_lazy_imports("all")
+ namespace = self.exec_with_path(tmp, "import pep810_aug_global_lazy")
+ lazy_proxy = namespace["pep810_aug_global_lazy"]
+ self.assertIsInstance(lazy_proxy, types.LazyImportType)
+ self.assertNotIn("pep810_aug_global_lazy", sys.modules)
+
+ sys.set_lazy_imports("none")
+ eager_namespace = self.exec_with_path(tmp, "lazy import pep810_aug_global_eager")
+ eager_module = eager_namespace["pep810_aug_global_eager"]
+ self.assertEqual(eager_module.FLAG, "eager")
+ self.assertIn("pep810_aug_global_eager", sys.modules)
+
+ def test_filter_controls_lazy_and_eager_outcomes(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_aug_filter_allowed", "VALUE = 'allowed'")
+ self.make_module(tmp, "pep810_aug_filter_blocked", "VALUE = 'blocked'")
+ calls = []
+
+ def import_filter(importer, name, fromlist):
+ calls.append((importer, name, fromlist))
+ return name.endswith("_allowed")
+
+ sys.set_lazy_imports_filter(import_filter)
+ namespace = self.exec_with_path(
+ tmp,
+ """
+ lazy import pep810_aug_filter_allowed
+ lazy import pep810_aug_filter_blocked
+ """,
+ )
+
+ self.assertIn(("pep810_aug_driver", "pep810_aug_filter_allowed", None), calls)
+ self.assertIn(("pep810_aug_driver", "pep810_aug_filter_blocked", None), calls)
+ self.assertIsInstance(namespace["pep810_aug_filter_allowed"], types.LazyImportType)
+ self.assertNotIn("pep810_aug_filter_allowed", sys.modules)
+ self.assertEqual(namespace["pep810_aug_filter_blocked"].VALUE, "blocked")
+ self.assertIn("pep810_aug_filter_blocked", sys.modules)
+
+ def test_valid_lazy_syntax_and_restrictions_are_enforced_together(self):
+ compile("lazy import math", "<pep810-valid>", "exec")
+
+ invalid_sources = [
+ "lazy from math import *",
+ "def f():\n lazy import math",
+ "class C:\n lazy import math",
+ "try:\n lazy import math\nexcept ImportError:\n pass",
+ "lazy from __future__ import annotations",
+ ]
+ for source in invalid_sources:
+ with self.subTest(source=source):
+ with self.assertRaises(SyntaxError):
+ compile(source, "<pep810-invalid>", "exec")
+
+ def test_compatibility_lazy_modules_marks_regular_import_lazy(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_aug_compat_target", "VALUE = 'compat'")
+ self.make_module(tmp, "pep810_aug_compat_importer", """
+ __lazy_modules__ = ["pep810_aug_compat_target"]
+ import pep810_aug_compat_target
+ """)
+ sys.path.insert(0, tmp)
+ self.addCleanup(lambda: sys.path.remove(tmp) if tmp in sys.path else None)
+
+ importer = importlib.import_module("pep810_aug_compat_importer")
+ self.assertNotIn("pep810_aug_compat_target", sys.modules)
+ proxy = importer.__dict__["pep810_aug_compat_target"]
+ self.assertIsInstance(proxy, types.LazyImportType)
+ self.assertEqual(proxy.resolve().VALUE, "compat")
+
+ def test_lazy_submodule_is_registered_on_parent_until_reified(self):
+ import test.test_import.data.lazy_imports.pkg.c as package_module
+
+ globals_dict = package_module.get_globals()
+ self.assertEqual(type(globals_dict["x"]), int)
+ self.assertIsInstance(globals_dict["b"], types.LazyImportType)
+ self.assertNotIn("test.test_import.data.lazy_imports.pkg.b", sys.modules)
+ resolved = globals_dict["b"].resolve()
+ self.assertEqual(resolved.__name__, "test.test_import.data.lazy_imports.pkg.b")
+ self.assertIn("test.test_import.data.lazy_imports.pkg.b", sys.modules)
+
+ def test_documented_lazy_builtin_handles_errors_and_tuple_fromlist(self):
+ with self.assertRaisesRegex(ValueError, "builtins"):
+ exec("__lazy_import__('pep810_aug_missing_builtins', {}, {}, (), 0)", {})
+
+ with self.assertRaisesRegex(TypeError, "expected str"):
+ self.exec_with_path(
+ tempfile.gettempdir(),
+ "__lazy_import__(42, globals(), globals(), (), 0)",
+ )
+
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_aug_direct_target", """
+ FIRST = "first"
+ SECOND = "second"
+ """)
+
+ namespace = self.exec_with_path(
+ tmp,
+ """
+ with_fromlist = __lazy_import__(
+ 'pep810_aug_direct_target', globals(), globals(), ('FIRST', 'SECOND'), 0
+ )
+ bad_fromlist = None
+ try:
+ __lazy_import__('pep810_aug_direct_target', globals(), globals(), object(), 0)
+ except TypeError as exc:
+ bad_fromlist = exc
+ """,
+ )
+
+ self.assertIsInstance(namespace["bad_fromlist"], TypeError)
+ proxy = namespace["with_fromlist"]
+ self.assertIsInstance(proxy, types.LazyImportType)
+ self.assertIn("pep810_aug_direct_target...", repr(proxy))
+ module = proxy.resolve()
+ self.assertEqual((module.FIRST, module.SECOND), ("first", "second"))
+
+ def test_relative_lazy_builtin_reifies_package_member(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_aug_relpkg.child", "VALUE = 'relative'")
+ sys.path.insert(0, tmp)
+ self.addCleanup(lambda: sys.path.remove(tmp) if tmp in sys.path else None)
+ importlib.import_module("pep810_aug_relpkg")
+
+ namespace = {
+ "__name__": "pep810_aug_relpkg.driver",
+ "__package__": "pep810_aug_relpkg",
+ "__file__": os.path.join(tmp, "pep810_aug_relpkg", "driver.py"),
+ }
+ exec(
+ "child_proxy = __lazy_import__('child', globals(), globals(), ('VALUE',), 1)",
+ namespace,
+ )
+
+ proxy = namespace["child_proxy"]
+ self.assertIsInstance(proxy, types.LazyImportType)
+ self.assertNotIn("pep810_aug_relpkg.child", sys.modules)
+ child = proxy.resolve()
+ self.assertEqual(child.VALUE, "relative")
+
+ def test_lazy_resolution_error_reports_declaration_site(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_aug_broken", """
+ raise RuntimeError("broken lazy target")
+ """)
+
+ namespace = self.exec_with_path(tmp, "lazy import pep810_aug_broken")
+ proxy = namespace["pep810_aug_broken"]
+
+ with self.assertRaisesRegex(RuntimeError, "broken lazy target") as caught:
+ proxy.resolve()
+
+ cause = caught.exception.__cause__
+ self.assertIsInstance(cause, ImportError)
+ self.assertIn("deferred import of 'pep810_aug_broken'", str(cause))
+ formatted = "".join(traceback.format_exception(caught.exception))
+ self.assertIn("deferred import of 'pep810_aug_broken'", formatted)
+
+ def test_traceback_suggestions_skip_lazy_module_attributes(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_aug_suggestion_target", "VALUE = 99")
+ sys.path.insert(0, tmp)
+ self.addCleanup(lambda: sys.path.remove(tmp) if tmp in sys.path else None)
+
+ holder = types.ModuleType("pep810_aug_holder")
+ holder.__file__ = os.path.join(tmp, "holder.py")
+ exec(
+ "lazy import pep810_aug_suggestion_target as missingg",
+ holder.__dict__,
+ )
+
+ self.assertIsInstance(holder.__dict__["missingg"], types.LazyImportType)
+ with self.assertRaises(AttributeError) as caught:
+ holder.missing
+
+ rendered = "".join(traceback.format_exception_only(caught.exception))
+ self.assertNotIn("missingg", rendered)
+ self.assertNotIn("pep810_aug_suggestion_target", sys.modules)
+
+ def test_dis_reports_lazy_and_eager_import_flags(self):
+ lazy_code = compile(
+ "lazy import pep810_aug_dis_target\n"
+ "lazy from pep810_aug_dis_target import VALUE\n",
+ "<pep810-dis-lazy>",
+ "exec",
+ )
+ lazy_imports = [
+ instr.argrepr
+ for instr in dis.get_instructions(lazy_code)
+ if instr.opname == "IMPORT_NAME"
+ ]
+ self.assertGreaterEqual(len(lazy_imports), 2)
+ self.assertTrue(all("+ lazy" in argrepr for argrepr in lazy_imports))
+
+ eager_code = compile(
+ "try:\n"
+ " import pep810_aug_dis_target\n"
+ "except ImportError:\n"
+ " pass\n",
+ "<pep810-dis-eager>",
+ "exec",
+ )
+ eager_imports = [
+ instr.argrepr
+ for instr in dis.get_instructions(eager_code)
+ if instr.opname == "IMPORT_NAME"
+ ]
+ self.assertTrue(any("+ eager" in argrepr for argrepr in eager_imports))
+
+ out = io.StringIO()
+ dis.dis(lazy_code, file=out)
+ self.assertIn("+ lazy", out.getvalue())
+
+ def test_command_line_lazy_modes_and_environment_precedence(self):
+ script = "import sys; print(sys.get_lazy_imports()); print(sys.flags.lazy_imports)"
+ env = os.environ.copy()
+ env["PYTHON_LAZY_IMPORTS"] = "all"
+
+ env_result = subprocess.run(
+ [sys.executable, "-c", script],
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ check=True,
+ env=env,
+ )
+ self.assertEqual(env_result.stdout.splitlines()[0], "all")
+
+ cli_result = subprocess.run(
+ [sys.executable, "-X", "lazy_imports=none", "-c", script],
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ check=True,
+ env=env,
+ )
+ lines = cli_result.stdout.splitlines()
+ self.assertEqual(lines[0], "none")
+ self.assertIn(lines[1], {"0", "none"})
+
+ def test_pep810_related_regression_modules_pass_in_subprocess(self):
+ runner = r"""
+import sys
+import unittest
+
+modules = [
+ "test.test_import.test_lazy_imports",
+ "test.test_dis",
+ "test.test_traceback",
+ "test.test_types",
+ "test.test_sys",
+ "test.test_pyrepl.test_utils",
+ "test.test_capi.test_config",
+]
+
+def iter_tests(suite):
+ for item in suite:
+ if isinstance(item, unittest.TestSuite):
+ yield from iter_tests(item)
+ else:
+ yield item
+
+loader = unittest.TestLoader()
+selected = unittest.TestSuite()
+for module in modules:
+ for test in iter_tests(loader.loadTestsFromName(module)):
+ if ".ThreadSafetyTests." in test.id():
+ continue
+ selected.addTest(test)
+
+result = unittest.TextTestRunner(verbosity=1).run(selected)
+sys.exit(0 if result.wasSuccessful() else 1)
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", runner],
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ self.assertEqual(
+ result.returncode,
+ 0,
+ f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/Lib/test/test_import/test_pep810_import_stability_aug.py b/Lib/test/test_import/test_pep810_import_stability_aug.py
new file mode 100644
index 00000000..00000000
--- /dev/null
+++ b/Lib/test/test_import/test_pep810_import_stability_aug.py
@@ -0,0 +1,93 @@
+"""Augmented P2P tests for import behavior not changed by PEP 810."""
+
+import importlib
+import os
+import pathlib
+import sys
+import tempfile
+import textwrap
+import unittest
+
+
+class ImportStabilityAugmentedTests(unittest.TestCase):
+ def tearDown(self):
+ for name in list(sys.modules):
+ if name.startswith("pep810_stability_"):
+ del sys.modules[name]
+
+ def make_module(self, directory, name, body):
+ path = pathlib.Path(directory, name + ".py")
+ path.write_text(textwrap.dedent(body), encoding="utf-8")
+
+ def with_path(self, directory):
+ sys.path.insert(0, directory)
+ self.addCleanup(lambda: sys.path.remove(directory) if directory in sys.path else None)
+
+ def test_lazy_identifier_remains_ordinary_name_outside_import_syntax(self):
+ namespace = {}
+ exec(
+ textwrap.dedent(
+ """
+ lazy = 3
+
+ class Holder:
+ lazy = 4
+
+ def echo(lazy):
+ return lazy + 1
+
+ result = lazy, Holder.lazy, echo(5)
+ """
+ ),
+ namespace,
+ )
+ self.assertEqual(namespace["result"], (3, 4, 6))
+
+ def test_regular_import_executes_module_immediately(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ marker = os.path.join(tmp, "imported")
+ self.make_module(tmp, "pep810_stability_eager", f"""
+ import pathlib
+ pathlib.Path({marker!r}).write_text("yes", encoding="utf-8")
+ VALUE = 7
+ """)
+ self.with_path(tmp)
+
+ module = importlib.import_module("pep810_stability_eager")
+ self.assertEqual(module.VALUE, 7)
+ self.assertTrue(os.path.exists(marker))
+ self.assertIn("pep810_stability_eager", sys.modules)
+
+ def test_regular_from_import_inside_function_stays_eager(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ marker = os.path.join(tmp, "from_imported")
+ self.make_module(tmp, "pep810_stability_from", f"""
+ import pathlib
+ pathlib.Path({marker!r}).write_text("yes", encoding="utf-8")
+ VALUE = 11
+ """)
+ self.with_path(tmp)
+
+ def load_value():
+ from pep810_stability_from import VALUE
+ return VALUE
+
+ self.assertEqual(load_value(), 11)
+ self.assertTrue(os.path.exists(marker))
+ self.assertIn("pep810_stability_from", sys.modules)
+
+ def test_regular_import_in_try_except_still_uses_standard_error_flow(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ self.make_module(tmp, "pep810_stability_try", "VALUE = 13")
+ self.with_path(tmp)
+
+ try:
+ import pep810_stability_try
+ except ImportError as exc:
+ self.fail(f"regular import unexpectedly failed: {exc!r}")
+
+ self.assertEqual(pep810_stability_try.VALUE, 13)
+
+
+if __name__ == "__main__":
+ unittest.main()
|