Skip to content

Commit 01189bd

Browse files
[3.13] gh-123011: Fix warn_explicit() with the globals of the __main__ module (GH-155318) (GH-155991)
The __main__ module executed as a script or a command has __spec__ set to None, so warn_explicit(module_globals=globals()) emitted a spurious DeprecationWarning. It also raised ImportError when the loader was unable to provide the source of the module: when the module was executed with -m (the loader can only handle its own module name) or as a command (the built-in importer has no source). (cherry picked from commit f2eaf17) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent a2773a3 commit 01189bd

4 files changed

Lines changed: 89 additions & 3 deletions

File tree

Lib/importlib/_bootstrap_external.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -916,6 +916,10 @@ def _bless_my_loader(module_globals):
916916
loader = module_globals.get('__loader__', None)
917917
spec = module_globals.get('__spec__', missing)
918918

919+
# The __main__ module of a script or the REPL has __spec__ set to None.
920+
if spec is None and module_globals.get('__name__') == '__main__':
921+
return loader
922+
919923
if loader is None:
920924
if spec is missing:
921925
# If working with a module:

Lib/test/test_warnings/__init__.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1581,6 +1581,59 @@ def test_issue_8766(self):
15811581
assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
15821582

15831583

1584+
class WarnExplicitMainTests(BaseTest):
1585+
# gh-123011: warn_explicit() with module globals of the __main__ module,
1586+
# no matter how it is executed.
1587+
code = ('import warnings\n'
1588+
'warnings.warn_explicit("eggs", UserWarning, "bar", 1,\n'
1589+
' module_globals=globals())\n')
1590+
1591+
def prepare_code(self):
1592+
"""Make the subprocess use the tested implementation."""
1593+
if self.module is py_warnings:
1594+
return ("import sys\n"
1595+
"sys.modules['_warnings'] = None\n") + self.code
1596+
return self.code
1597+
1598+
def check(self, err):
1599+
lines = err.decode().splitlines()
1600+
# Only the Python implementation adds the source line.
1601+
if len(lines) > 1 and lines[1].startswith(' '):
1602+
del lines[1]
1603+
self.assertEqual(lines, ['bar:1: UserWarning: eggs'])
1604+
1605+
def make_script(self, dirname):
1606+
filename = os.path.join(dirname, 'spam.py')
1607+
with open(filename, 'w', encoding='utf-8') as f:
1608+
f.write(self.prepare_code())
1609+
return filename
1610+
1611+
def test_script(self):
1612+
# __main__ has __spec__ set to None.
1613+
with os_helper.temp_dir() as dirname:
1614+
filename = self.make_script(dirname)
1615+
rc, out, err = assert_python_ok(filename)
1616+
self.check(err)
1617+
1618+
def test_module(self):
1619+
# __main__ has __spec__ of the module executed with -m.
1620+
with os_helper.temp_dir() as dirname:
1621+
self.make_script(dirname)
1622+
rc, out, err = assert_python_ok('-m', 'spam', PYTHONPATH=dirname)
1623+
self.check(err)
1624+
1625+
def test_command(self):
1626+
# __main__ has the built-in importer as a loader.
1627+
rc, out, err = assert_python_ok('-c', self.prepare_code())
1628+
self.check(err)
1629+
1630+
class CWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase):
1631+
module = c_warnings
1632+
1633+
class PyWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase):
1634+
module = py_warnings
1635+
1636+
15841637
class FinalizationTest(unittest.TestCase):
15851638
def test_finalization(self):
15861639
# Issue #19421: warnings.warn() should not crash
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`warnings.warn_explicit` no longer emits a spurious
2+
:exc:`DeprecationWarning` or raises :exc:`ImportError` when it is called with
3+
the globals of the :mod:`__main__` module.

Python/_warnings.c

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,12 +1068,33 @@ get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno
10681068
return NULL;
10691069
}
10701070

1071-
int rc = PyDict_GetItemRef(module_globals, &_Py_ID(__name__),
1072-
&module_name);
1073-
if (rc < 0 || rc == 0) {
1071+
/* Prefer __spec__.name: __name__ is "__main__" for the module executed
1072+
as a script, but the loader can only handle its own module name. */
1073+
PyObject *spec;
1074+
if (PyDict_GetItemRef(module_globals, &_Py_ID(__spec__), &spec) < 0) {
10741075
Py_DECREF(loader);
10751076
return NULL;
10761077
}
1078+
module_name = NULL;
1079+
if (spec != NULL) {
1080+
int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(name), &module_name);
1081+
Py_DECREF(spec);
1082+
if (rc < 0) {
1083+
Py_DECREF(loader);
1084+
return NULL;
1085+
}
1086+
if (module_name == Py_None) {
1087+
Py_CLEAR(module_name);
1088+
}
1089+
}
1090+
if (module_name == NULL) {
1091+
int rc = PyDict_GetItemRef(module_globals, &_Py_ID(__name__),
1092+
&module_name);
1093+
if (rc <= 0) { // not found or error
1094+
Py_DECREF(loader);
1095+
return NULL;
1096+
}
1097+
}
10771098

10781099
/* Make sure the loader implements the optional get_source() method. */
10791100
(void)PyObject_GetOptionalAttr(loader, &_Py_ID(get_source), &get_source);
@@ -1087,6 +1108,11 @@ get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno
10871108
Py_DECREF(get_source);
10881109
Py_DECREF(module_name);
10891110
if (!source) {
1111+
/* The source line is optional: the loader can be unable to provide
1112+
the source of the module, for example if it is not its loader. */
1113+
if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1114+
PyErr_Clear();
1115+
}
10901116
return NULL;
10911117
}
10921118
if (source == Py_None) {

0 commit comments

Comments
 (0)