Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Lib/test/test_lazy_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,19 @@ def test_lazy_import_type_attribute_error_message(self):
""")
assert_python_ok("-c", code)

@support.run_with_limited_c_stack(depth=10_000, size=256 * 1024)
def test_deeply_dotted_name(self):
"""A long dotted name must not overflow the C stack."""
m = types.SimpleNamespace()
# Every lookup in m.m.m... succeeds, so resolve() only fails if the
# C stack runs out.
m.m = m
ns = {"__builtins__": {"__lazy_import__": __lazy_import__,
"__import__": lambda *args: m}}
exec("lazy import " + ".".join(["m"] * 10_000) + " as x", ns)
with contextlib.suppress(RecursionError):
ns["x"].resolve()


class SyntaxRestrictionTests(LazyImportTestCase):
"""Tests for syntax restrictions on lazy imports."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a crash when walking a very long chain of lazy import placeholders, as
created by an aliased dotted import such as ``lazy import a.b.c as d``.
:exc:`RecursionError` is now raised instead.
8 changes: 8 additions & 0 deletions Objects/lazyimportobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,11 @@ static PyObject *
lazy_import_path(PyLazyImportObject *m)
{
if (PyLazyImport_CheckExact(m->lz_from)) {
if (_Py_EnterRecursiveCall(" while getting the name of a lazy import")) {
return NULL;
}
PyObject *base = lazy_import_path((PyLazyImportObject *)m->lz_from);
_Py_LeaveRecursiveCall();
if (base == NULL) {
return NULL;
}
Expand Down Expand Up @@ -277,8 +281,12 @@ lazy_import_replay_from(PyThreadState *tstate, PyObject *mod,
if (!PyLazyImport_CheckExact(lz->lz_from)) {
return Py_NewRef(mod);
}
if (_Py_EnterRecursiveCallTstate(tstate, " while resolving a lazy import")) {
return NULL;
}
PyObject *from = lazy_import_replay_from(
tstate, mod, (PyLazyImportObject *)lz->lz_from);
_Py_LeaveRecursiveCallTstate(tstate);
if (from == NULL) {
return NULL;
}
Expand Down
Loading