Skip to content

Commit 1a2d24e

Browse files
[3.15] gh-157757: Fix to make lazy import a.b as c import the module a.b (GH-158092) (#158257)
gh-157757: Fix to make `lazy import a.b as c` import the module `a.b` (#158092) * Import the module a lazy `import a.b as c` names `import a.b as c` compiles to `IMPORT_NAME a.b` followed by `IMPORT_FROM b`. Lazily, IMPORT_NAME leaves a placeholder holding "a.b", and IMPORT_FROM rewrote it into the placeholder `lazy from a import b` produces. Reification then imported `a` alone and read `b` off it, so the module `a.b` was never imported under its own name: an attribute of the package shadowing it answered instead, and `math.pi`, which no module backs, bound the float where the eager statement raises ModuleNotFoundError. Mark the dotted import on the placeholder and keep the whole name on it. Reification imports that name and then walks its components with IMPORT_FROM, which is what the eager statement does. The test pinning `lazy import math.pi as pi` as working is inverted, since the eager statement raises. * Stop excluding test_trace from the lazy-imports-all run It passes now that a lazy `import a.b as c` imports the module: the KeyError on 'test.tracedmodules.testmod' came from the submodule never being imported under its own name. * Rename lz_submodule to lz_dotted_as and trim the comments The flag means "bind the whole dotted name, not the root", which the old name did not say, and import.c already has unrelated lazy_pending_submodules machinery to be confused with. * Chain lazy IMPORT_FROM placeholders instead of flagging dotted imports Each deferred IMPORT_FROM off a placeholder without a fromlist now keeps the previous placeholder in lz_from and the attribute name in lz_attr. Reification walks back to the placeholder IMPORT_NAME left, runs that import, and replays the lookups in order with _PyEval_ImportFrom, which is what the eager bytecode does. This drops the lz_dotted_as flag and also follows a custom __lazy_import__ that returns a placeholder for a different module name. * Chain every deferred IMPORT_FROM onto the previous placeholder `lazy from a import b` now records its lookup the same way as `import a.b as c`, so a placeholder holds either the module name and fromlist or the previous placeholder and an attribute name, and reification has a single path. The import passes only the name being resolved as the fromlist, so accessing b still does not import the other names' submodules. * Treat an empty fromlist on a lazy import placeholder as no fromlist __import__("a.b", fromlist=()) returns the top-level package `a`, the same as fromlist=None, but the placeholder kept the empty tuple. Every consumer of lz_attr then read it as a real fromlist: reification narrowed it to the chained attribute and replayed the lookups on `a.b`, _PyEval_LazyImportFrom took the attribute off sys.modules["a.b"], and the repr named `a.b.attr`. _PyLazyImport_New already collapses None to NULL for exactly this reason, so collapse an empty tuple there too and every site follows. * gh-157757: Preserve empty fromlists for custom import hooks --------- (cherry picked from commit 1e8ff18) Co-authored-by: Brittany Reynoso <breynoso@meta.com>
1 parent 8f36ce3 commit 1a2d24e

6 files changed

Lines changed: 242 additions & 62 deletions

File tree

‎Lib/test/test_lazy_import/__init__.py‎

Lines changed: 149 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -732,10 +732,17 @@ def test_non_package_lazily_imported(self):
732732
assert_python_ok("-c", code)
733733

734734
def test_non_package_lazily_imported_as(self):
735-
"""Doing a dotted lazy import as still works"""
735+
"""A dotted lazy import as raises when the name is not a module."""
736+
# gh-157757: the eager statement raises, so the lazy one raises too.
736737
code = textwrap.dedent("""
737738
lazy import math.pi as pi
738-
pi
739+
740+
try:
741+
pi
742+
except ModuleNotFoundError:
743+
pass
744+
else:
745+
raise AssertionError("ModuleNotFoundError was not raised")
739746
""")
740747
assert_python_ok("-c", code)
741748

@@ -1178,6 +1185,22 @@ def test_accessing_one_name_leaves_others_as_proxies(self):
11781185
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
11791186
self.assertIn("OK", result.stdout)
11801187

1188+
def test_accessing_one_name_imports_only_its_submodule(self):
1189+
"""Accessing one name should not import the other names' submodules."""
1190+
code = textwrap.dedent("""
1191+
import sys
1192+
1193+
lazy from test.test_lazy_import.data.pkg import b, bar, broken
1194+
1195+
# Importing bar prints, and importing broken raises.
1196+
b.foo()
1197+
1198+
assert "test.test_lazy_import.data.pkg.bar" not in sys.modules
1199+
assert "test.test_lazy_import.data.pkg.broken" not in sys.modules
1200+
""")
1201+
rc, out, err = assert_python_ok("-c", code)
1202+
self.assertEqual(out, b"")
1203+
11811204
def test_all_names_reified_after_all_accessed(self):
11821205
"""All names should be reified after each is accessed."""
11831206
code = textwrap.dedent("""
@@ -2144,5 +2167,129 @@ def test_dunder_lazy_import_without_frame(self):
21442167
)
21452168

21462169

2170+
class DottedLazyImportTests(unittest.TestCase):
2171+
2172+
def test_lazy_import_as_wins_over_variable(self):
2173+
"""A dotted lazy import as imports the submodule the variable hides."""
2174+
# gh-157757: importing pkg.b rebinds pkg.b from the variable to the
2175+
# module, eagerly and lazily alike.
2176+
code = textwrap.dedent("""
2177+
import sys
2178+
import test.test_lazy_import.data.pkg as pkg
2179+
pkg.b = "hides the b submodule"
2180+
2181+
lazy import test.test_lazy_import.data.pkg.b as b
2182+
lazy import xml.dom.minidom as minidom
2183+
2184+
assert b is sys.modules["test.test_lazy_import.data.pkg.b"], b
2185+
assert minidom is sys.modules["xml.dom.minidom"], minidom
2186+
""")
2187+
assert_python_ok("-c", code)
2188+
2189+
2190+
def test_dotted_as_of_loaded_module(self):
2191+
"""A dotted lazy import as binds the module, not a same-named attribute."""
2192+
# importlib.metadata is already loaded and has a `metadata` attribute.
2193+
code = textwrap.dedent("""
2194+
import importlib.metadata
2195+
import importlib.metadata as eager
2196+
2197+
lazy import importlib.metadata as lazily
2198+
2199+
assert lazily is eager, lazily
2200+
""")
2201+
assert_python_ok("-c", code)
2202+
2203+
2204+
def test_dotted_as_replays_lookups_on_custom_placeholder(self):
2205+
"""A dotted lazy import as looks up its names on what the hook returned."""
2206+
code = textwrap.dedent("""
2207+
import builtins
2208+
import xml.dom
2209+
2210+
# In a list, so the hook reading it does not resolve it.
2211+
placeholder = [__lazy_import__("xml")]
2212+
default = builtins.__lazy_import__
2213+
builtins.__lazy_import__ = lambda *args: placeholder[0]
2214+
lazy import fake.dom as dom
2215+
builtins.__lazy_import__ = default
2216+
2217+
assert dom is xml.dom, dom
2218+
""")
2219+
assert_python_ok("-c", code)
2220+
2221+
2222+
def test_empty_fromlist_placeholder_matches_no_fromlist(self):
2223+
"""An empty fromlist behaves like None."""
2224+
code = textwrap.dedent("""
2225+
expected = "<lazy_import 'xml.dom'>"
2226+
# In lists, so reading them does not resolve them.
2227+
for fromlist in (None, ()):
2228+
same = [__lazy_import__("xml.dom", fromlist=fromlist)]
2229+
assert repr(same[0]) == expected, (fromlist, repr(same[0]))
2230+
bare = [__lazy_import__("xml.dom")]
2231+
assert repr(bare[0]) == expected, repr(bare[0])
2232+
""")
2233+
assert_python_ok("-c", code)
2234+
2235+
2236+
def test_empty_fromlist_preserved_for_custom_import(self):
2237+
code = textwrap.dedent("""
2238+
import builtins
2239+
import types
2240+
2241+
value = object()
2242+
module = types.SimpleNamespace(dom=value)
2243+
placeholder = [__lazy_import__("xml.dom", fromlist=())]
2244+
default_import = builtins.__import__
2245+
default_lazy_import = builtins.__lazy_import__
2246+
calls = []
2247+
2248+
def import_hook(name, globals, locals, fromlist, level):
2249+
assert name == "xml.dom", name
2250+
assert fromlist == (), fromlist
2251+
calls.append(fromlist)
2252+
return module
2253+
2254+
builtins.__import__ = import_hook
2255+
assert placeholder[0].resolve() is module
2256+
builtins.__lazy_import__ = lambda *args: placeholder[0]
2257+
lazy import fake.dom as dom
2258+
assert dom is value
2259+
builtins.__import__ = default_import
2260+
builtins.__lazy_import__ = default_lazy_import
2261+
2262+
assert calls == [(), ()], calls
2263+
""")
2264+
assert_python_ok("-c", code)
2265+
2266+
2267+
def test_dotted_as_replays_lookups_on_dotted_placeholder(self):
2268+
"""A dotted lazy import as replays its names on the hook's package."""
2269+
# importlib.metadata has a `metadata` attribute of its own, which the
2270+
# placeholder for importlib must not answer with.
2271+
for target in ("xml.dom", "importlib.metadata"):
2272+
with self.subTest(target=target):
2273+
leaf = target.rpartition(".")[2]
2274+
code = textwrap.dedent(f"""
2275+
import builtins
2276+
import sys
2277+
import {target}
2278+
2279+
# In a list, so the hook reading it does not resolve it.
2280+
placeholder = [__lazy_import__("{target}", fromlist=())]
2281+
default = builtins.__lazy_import__
2282+
builtins.__lazy_import__ = lambda *args: placeholder[0]
2283+
lazy import fake.{leaf} as {leaf}
2284+
builtins.__lazy_import__ = default
2285+
2286+
name = repr(globals()["{leaf}"])
2287+
assert name == "<lazy_import '{target}'>", name
2288+
assert {leaf} is sys.modules["{target}"], {leaf}
2289+
""")
2290+
assert_python_ok("-c", code)
2291+
2292+
2293+
21472294
if __name__ == '__main__':
21482295
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Submodule that raises an error during import
2+
raise ValueError("This module always fails to import")
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a lazy ``import a.b as c`` reading ``b`` off ``a`` instead of importing
2+
the module ``a.b``. It now binds the submodule, and raises
3+
:exc:`ModuleNotFoundError` when no module backs the name.

‎Objects/lazyimportobject.c‎

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ PyObject *
1414
_PyLazyImport_New(_PyInterpreterFrame *frame, PyObject *builtins, PyObject *name, PyObject *fromlist)
1515
{
1616
PyLazyImportObject *m;
17-
if (!name || !PyUnicode_Check(name)) {
18-
PyErr_SetString(PyExc_TypeError, "expected str for name");
17+
if (!name || !(PyUnicode_Check(name) || PyLazyImport_CheckExact(name))) {
18+
PyErr_SetString(PyExc_TypeError, "expected str or lazy_import for name");
1919
return NULL;
2020
}
2121
if (fromlist == Py_None || fromlist == NULL) {
@@ -104,16 +104,45 @@ lazy_import_getattro(PyObject *op, PyObject *name)
104104
return value;
105105
}
106106

107+
// The dotted name of the object that resolving the placeholder returns.
107108
static PyObject *
108-
lazy_import_name(PyLazyImportObject *m)
109+
lazy_import_path(PyLazyImportObject *m)
109110
{
110-
if (m->lz_attr != NULL) {
111-
if (PyUnicode_Check(m->lz_attr)) {
112-
return PyUnicode_FromFormat("%U.%U", m->lz_from, m->lz_attr);
113-
}
114-
else {
115-
return PyUnicode_FromFormat("%U...", m->lz_from);
111+
if (PyLazyImport_CheckExact(m->lz_from)) {
112+
PyObject *base = lazy_import_path((PyLazyImportObject *)m->lz_from);
113+
if (base == NULL) {
114+
return NULL;
116115
}
116+
PyObject *res = PyUnicode_FromFormat("%U.%U", base, m->lz_attr);
117+
Py_DECREF(base);
118+
return res;
119+
}
120+
if (m->lz_attr != NULL &&
121+
(!PyTuple_Check(m->lz_attr) || PyTuple_GET_SIZE(m->lz_attr) > 0)) {
122+
return Py_NewRef(m->lz_from);
123+
}
124+
// __import__("a.b") returns the top-level package `a`.
125+
Py_ssize_t dot = PyUnicode_FindChar(
126+
m->lz_from, '.', 0, PyUnicode_GET_LENGTH(m->lz_from), 1
127+
);
128+
if (dot == -2) {
129+
return NULL;
130+
}
131+
if (dot < 0) {
132+
return Py_NewRef(m->lz_from);
133+
}
134+
return PyUnicode_Substring(m->lz_from, 0, dot);
135+
}
136+
137+
static PyObject *
138+
lazy_import_name(PyLazyImportObject *m)
139+
{
140+
if (PyLazyImport_CheckExact(m->lz_from)) {
141+
return lazy_import_path(m);
142+
}
143+
if (m->lz_attr != NULL &&
144+
(!PyTuple_Check(m->lz_attr) || PyTuple_GET_SIZE(m->lz_attr) > 0)) {
145+
return PyUnicode_FromFormat("%U...", m->lz_from);
117146
}
118147
return Py_NewRef(m->lz_from);
119148
}

‎Python/ceval.c‎

Lines changed: 8 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3310,7 +3310,13 @@ _PyEval_LazyImportFrom(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObje
33103310
assert(PyUnicode_Check(name));
33113311
PyObject *ret;
33123312
PyLazyImportObject *d = (PyLazyImportObject *)v;
3313-
PyObject *mod = PyImport_GetModule(d->lz_from);
3313+
PyObject *mod = NULL;
3314+
// Only `from a import b` can take b off an already imported a;
3315+
// `import a.b as c` has to import a.b first.
3316+
if (d->lz_attr != NULL && PyTuple_Check(d->lz_attr) &&
3317+
PyTuple_GET_SIZE(d->lz_attr) > 0) {
3318+
mod = PyImport_GetModule(d->lz_from);
3319+
}
33143320
if (mod != NULL) {
33153321
// Check if the module already has the attribute, if so, resolve it
33163322
// eagerly.
@@ -3330,34 +3336,7 @@ _PyEval_LazyImportFrom(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObje
33303336
Py_DECREF(mod);
33313337
}
33323338

3333-
if (d->lz_attr != NULL) {
3334-
if (PyUnicode_Check(d->lz_attr)) {
3335-
PyObject *from = PyUnicode_FromFormat(
3336-
"%U.%U", d->lz_from, d->lz_attr);
3337-
if (from == NULL) {
3338-
return NULL;
3339-
}
3340-
ret = _PyLazyImport_New(frame, d->lz_builtins, from, name);
3341-
Py_DECREF(from);
3342-
return ret;
3343-
}
3344-
}
3345-
else {
3346-
Py_ssize_t dot = PyUnicode_FindChar(
3347-
d->lz_from, '.', 0, PyUnicode_GET_LENGTH(d->lz_from), 1
3348-
);
3349-
if (dot >= 0) {
3350-
PyObject *from = PyUnicode_Substring(d->lz_from, 0, dot);
3351-
if (from == NULL) {
3352-
return NULL;
3353-
}
3354-
ret = _PyLazyImport_New(frame, d->lz_builtins, from, name);
3355-
Py_DECREF(from);
3356-
return ret;
3357-
}
3358-
}
3359-
ret = _PyLazyImport_New(frame, d->lz_builtins, d->lz_from, name);
3360-
return ret;
3339+
return _PyLazyImport_New(frame, d->lz_builtins, v, name);
33613340
}
33623341

33633342
#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\

0 commit comments

Comments
 (0)