Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Add input validation to _PyImport_LazyImportModuleLevelObject
  • Loading branch information
StanFromIreland committed Feb 21, 2026
commit e160e5ce22285365507aec70d21787073aa258d7
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_non_string_name(self):
"""__lazy_import__ should reject non-string name arguments."""
with self.assertRaises(TypeError):
__lazy_import__(b"")
with self.assertRaises(TypeError):
__lazy_import__(123)
with self.assertRaises(TypeError):
__lazy_import__(None)
Comment thread
StanFromIreland marked this conversation as resolved.
Outdated

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.
14 changes: 14 additions & 0 deletions Python/import.c
Original file line number Diff line number Diff line change
Expand Up @@ -4468,6 +4468,20 @@ _PyImport_LazyImportModuleLevelObject(PyThreadState *tstate,
PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
{
if (name == NULL) {
_PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
return NULL;
}
Comment thread
StanFromIreland marked this conversation as resolved.
Outdated
if (!PyUnicode_Check(name)) {
_PyErr_SetString(tstate, PyExc_TypeError,
"module name must be a string");
Comment thread
StanFromIreland marked this conversation as resolved.
Outdated
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