Skip to content

Commit 225985c

Browse files
lazergmiss-islington
authored andcommitted
gh-161229: Accept None for globals and locals in __lazy_import__() (GH-161231)
(cherry picked from commit 1941319) Co-authored-by: Lazizbek Ergashev <lazerg2@gmail.com>
1 parent 1e4d32a commit 225985c

3 files changed

Lines changed: 18 additions & 2 deletions

File tree

‎Lib/test/test_lazy_import/__init__.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,20 @@ def test_dunder_lazy_import_invalid_arguments(self):
778778
b"TypeError: Item in ``from list'' must be str, not int",
779779
result.err)
780780

781+
@support.requires_subprocess()
782+
def test_dunder_lazy_import_explicit_none(self):
783+
"""__lazy_import__ should accept None for globals and locals."""
784+
code = textwrap.dedent("""
785+
import sys
786+
import types
787+
788+
lazy = __lazy_import__("test.test_lazy_import.data.basic2",
789+
globals=None, locals=None)
790+
assert type(globals()["lazy"]) is types.LazyImportType
791+
assert "test.test_lazy_import.data.basic2" not in sys.modules
792+
""")
793+
assert_python_ok("-c", code)
794+
781795
def test_dunder_lazy_import_builtins(self):
782796
"""__lazy_import__ should use module's __builtins__ for __import__."""
783797
from test.test_lazy_import.data import dunder_lazy_import_builtins
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:func:`!__lazy_import__` now treats ``None`` for *globals* and *locals* the
2+
same as omitting them, matching its signature.

‎Python/bltinmodule.c‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ builtin___lazy_import___impl(PyObject *module, PyObject *name,
311311
{
312312
PyObject *builtins;
313313
PyThreadState *tstate = PyThreadState_GET();
314-
if (globals == NULL) {
314+
if (globals == NULL || globals == Py_None) {
315315
globals = PyEval_GetGlobals();
316316
if (globals == NULL) {
317317
PyErr_SetString(PyExc_TypeError,
@@ -320,7 +320,7 @@ builtin___lazy_import___impl(PyObject *module, PyObject *name,
320320
return NULL;
321321
}
322322
}
323-
if (locals == NULL) {
323+
if (locals == NULL || locals == Py_None) {
324324
locals = globals;
325325
}
326326

0 commit comments

Comments
 (0)