Skip to content

Commit 3833fa9

Browse files
[3.15] gh-123011: Fix warn_explicit() with the globals of the __main__ module (GH-155318) (GH-155989)
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 701044d commit 3833fa9

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
@@ -634,6 +634,10 @@ def _bless_my_loader(module_globals):
634634
loader = module_globals.get('__loader__', None)
635635
spec = module_globals.get('__spec__', missing)
636636

637+
# The __main__ module of a script or the REPL has __spec__ set to None.
638+
if spec is None and module_globals.get('__name__') == '__main__':
639+
return loader
640+
637641
if loader is None:
638642
if spec is missing:
639643
# 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
@@ -1706,6 +1706,59 @@ def test_issue_8766(self):
17061706
assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
17071707

17081708

1709+
class WarnExplicitMainTests(BaseTest):
1710+
# gh-123011: warn_explicit() with module globals of the __main__ module,
1711+
# no matter how it is executed.
1712+
code = ('import warnings\n'
1713+
'warnings.warn_explicit("eggs", UserWarning, "bar", 1,\n'
1714+
' module_globals=globals())\n')
1715+
1716+
def prepare_code(self):
1717+
"""Make the subprocess use the tested implementation."""
1718+
if self.module is py_warnings:
1719+
return ("import sys\n"
1720+
"sys.modules['_warnings'] = None\n") + self.code
1721+
return self.code
1722+
1723+
def check(self, err):
1724+
lines = err.decode().splitlines()
1725+
# Only the Python implementation adds the source line.
1726+
if len(lines) > 1 and lines[1].startswith(' '):
1727+
del lines[1]
1728+
self.assertEqual(lines, ['bar:1: UserWarning: eggs'])
1729+
1730+
def make_script(self, dirname):
1731+
filename = os.path.join(dirname, 'spam.py')
1732+
with open(filename, 'w', encoding='utf-8') as f:
1733+
f.write(self.prepare_code())
1734+
return filename
1735+
1736+
def test_script(self):
1737+
# __main__ has __spec__ set to None.
1738+
with os_helper.temp_dir() as dirname:
1739+
filename = self.make_script(dirname)
1740+
rc, out, err = assert_python_ok(filename)
1741+
self.check(err)
1742+
1743+
def test_module(self):
1744+
# __main__ has __spec__ of the module executed with -m.
1745+
with os_helper.temp_dir() as dirname:
1746+
self.make_script(dirname)
1747+
rc, out, err = assert_python_ok('-m', 'spam', PYTHONPATH=dirname)
1748+
self.check(err)
1749+
1750+
def test_command(self):
1751+
# __main__ has the built-in importer as a loader.
1752+
rc, out, err = assert_python_ok('-c', self.prepare_code())
1753+
self.check(err)
1754+
1755+
class CWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase):
1756+
module = c_warnings
1757+
1758+
class PyWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase):
1759+
module = py_warnings
1760+
1761+
17091762
class FinalizationTest(unittest.TestCase):
17101763
def test_finalization(self):
17111764
# 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
@@ -1201,12 +1201,33 @@ get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno
12011201
return NULL;
12021202
}
12031203

1204-
int rc = PyDict_GetItemRef(module_globals, &_Py_ID(__name__),
1205-
&module_name);
1206-
if (rc < 0 || rc == 0) {
1204+
/* Prefer __spec__.name: __name__ is "__main__" for the module executed
1205+
as a script, but the loader can only handle its own module name. */
1206+
PyObject *spec;
1207+
if (PyDict_GetItemRef(module_globals, &_Py_ID(__spec__), &spec) < 0) {
12071208
Py_DECREF(loader);
12081209
return NULL;
12091210
}
1211+
module_name = NULL;
1212+
if (spec != NULL) {
1213+
int rc = PyObject_GetOptionalAttr(spec, &_Py_ID(name), &module_name);
1214+
Py_DECREF(spec);
1215+
if (rc < 0) {
1216+
Py_DECREF(loader);
1217+
return NULL;
1218+
}
1219+
if (module_name == Py_None) {
1220+
Py_CLEAR(module_name);
1221+
}
1222+
}
1223+
if (module_name == NULL) {
1224+
int rc = PyDict_GetItemRef(module_globals, &_Py_ID(__name__),
1225+
&module_name);
1226+
if (rc <= 0) { // not found or error
1227+
Py_DECREF(loader);
1228+
return NULL;
1229+
}
1230+
}
12101231

12111232
/* Make sure the loader implements the optional get_source() method. */
12121233
(void)PyObject_GetOptionalAttr(loader, &_Py_ID(get_source), &get_source);
@@ -1220,6 +1241,11 @@ get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno
12201241
Py_DECREF(get_source);
12211242
Py_DECREF(module_name);
12221243
if (!source) {
1244+
/* The source line is optional: the loader can be unable to provide
1245+
the source of the module, for example if it is not its loader. */
1246+
if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1247+
PyErr_Clear();
1248+
}
12231249
return NULL;
12241250
}
12251251
if (source == Py_None) {

0 commit comments

Comments
 (0)