Skip to content
Merged
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
9 changes: 9 additions & 0 deletions Lib/test/test_import/test_lazy_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,15 @@ def test_dunder_lazy_import_used(self):
import test.test_import.data.lazy_imports.dunder_lazy_import_used
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)

def test_dunder_lazy_import_invalid_arguments(self):
"""__lazy_import__ should reject invalid arguments."""
for invalid_name in (b"", 123, None):
with self.assertRaises(TypeError):
__lazy_import__(invalid_name)

with self.assertRaises(ValueError):
__lazy_import__("sys", level=-1)

def test_dunder_lazy_import_builtins(self):
"""__lazy_import__ should use module's __builtins__ for __import__."""
from test.test_import.data.lazy_imports import dunder_lazy_import_builtins
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a crash when :func:`!__lazy_import__` is passed a non-string argument,
by raising an :exc:`TypeError` instead.
11 changes: 11 additions & 0 deletions Python/import.c
Original file line number Diff line number Diff line change
Expand Up @@ -4468,6 +4468,17 @@ _PyImport_LazyImportModuleLevelObject(PyThreadState *tstate,
PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
{
assert(name != NULL);
if (!PyUnicode_Check(name)) {
_PyErr_Format(tstate, PyExc_TypeError,
"module name must be a string, got %T", name);
return NULL;
}
if (level < 0) {
_PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
return NULL;
}

PyObject *abs_name = get_abs_name(tstate, name, globals, level);
if (abs_name == NULL) {
return NULL;
Expand Down
Loading