Skip to content

Commit 3e63300

Browse files
gh-144957: Add test for lazy imports with __getattr__
Adds regression test to verify lazy imports work correctly with modules that use __getattr__ for dynamic attributes (e.g. typing.Match). The issue appears to be already fixed in current main branch.
1 parent 06b0920 commit 3e63300

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
"""Test module with __getattr__ for gh-144957."""
2+
3+
def __getattr__(name):
4+
"""Provide dynamic attributes."""
5+
if name == "dynamic_attr":
6+
return "from_getattr"
7+
raise AttributeError(f"module has no attribute {name!r}")

Lib/test/test_import/test_lazy_imports.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,23 @@ def test_basic_used(self):
8585
import test.test_import.data.lazy_imports.basic_used
8686
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
8787

88+
def test_lazy_import_with_getattr(self):
89+
"""Lazy imports work with module __getattr__ (gh-144957)."""
90+
code = textwrap.dedent("""
91+
import sys
92+
sys.set_lazy_imports("normal")
93+
lazy from test.test_import.data.lazy_imports.module_with_getattr import dynamic_attr
94+
assert dynamic_attr == "from_getattr"
95+
print("OK")
96+
""")
97+
result = subprocess.run(
98+
[sys.executable, "-c", code],
99+
capture_output=True,
100+
text=True
101+
)
102+
self.assertEqual(result.returncode, 0, result.stderr)
103+
self.assertIn("OK", result.stdout)
104+
88105

89106
class GlobalLazyImportModeTests(unittest.TestCase):
90107
"""Tests for sys.set_lazy_imports() global mode control."""

0 commit comments

Comments
 (0)