gh-118761: Add helper to ensure that lazy imports are actually lazy (#132614)

This ensures that if we jump through some hoops to make sure something is imported
lazily, we don't regress on importing it.

I recently already accidentally made typing import warnings and annotationlib eagerly.

Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
This commit is contained in:
Jelle Zijlstra 2025-04-16 20:46:36 -07:00 committed by GitHub
parent b530e174a3
commit 39ee468e09
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 39 additions and 0 deletions

View file

@ -5,6 +5,7 @@ import importlib.util
import os
import shutil
import sys
import textwrap
import unittest
import warnings
@ -309,3 +310,25 @@ def ready_to_import(name=None, source=""):
sys.modules[name] = old_module
else:
sys.modules.pop(name, None)
def ensure_lazy_imports(imported_module, modules_to_block):
"""Test that when imported_module is imported, none of the modules in
modules_to_block are imported as a side effect."""
modules_to_block = frozenset(modules_to_block)
script = textwrap.dedent(
f"""
import sys
modules_to_block = {modules_to_block}
if unexpected := modules_to_block & sys.modules.keys():
startup = ", ".join(unexpected)
raise AssertionError(f'unexpectedly imported at startup: {{startup}}')
import {imported_module}
if unexpected := modules_to_block & sys.modules.keys():
after = ", ".join(unexpected)
raise AssertionError(f'unexpectedly imported after importing {imported_module}: {{after}}')
"""
)
from .script_helper import assert_python_ok
assert_python_ok("-S", "-c", script)