mirror of
https://github.com/python/cpython.git
synced 2025-08-04 17:08:35 +00:00
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:
parent
b530e174a3
commit
39ee468e09
3 changed files with 39 additions and 0 deletions
|
@ -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)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue