Skip to content

Commit c6eff35

Browse files
serhiy-storchakamiss-islington
authored andcommitted
gh-123011: Fix warn_explicit() with the globals of the __main__ module (GH-155318)
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 ac4e5d2 commit c6eff35

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
@@ -1675,6 +1675,59 @@ def test_issue_8766(self):
16751675
assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
16761676

16771677

1678+
class WarnExplicitMainTests(BaseTest):
1679+
# gh-123011: warn_explicit() with module globals of the __main__ module,
1680+
# no matter how it is executed.
1681+
code = ('import warnings\n'
1682+
'warnings.warn_explicit("eggs", UserWarning, "bar", 1,\n'
1683+
' module_globals=globals())\n')
1684+
1685+
def prepare_code(self):
1686+
"""Make the subprocess use the tested implementation."""
1687+
if self.module is py_warnings:
1688+
return ("import sys\n"
1689+
"sys.modules['_warnings'] = None\n") + self.code
1690+
return self.code
1691+
1692+
def check(self, err):
1693+
lines = err.decode().splitlines()
1694+
# Only the Python implementation adds the source line.
1695+
if len(lines) > 1 and lines[1].startswith(' '):
1696+
del lines[1]
1697+
self.assertEqual(lines, ['bar:1: UserWarning: eggs'])
1698+
1699+
def make_script(self, dirname):
1700+
filename = os.path.join(dirname, 'spam.py')
1701+
with open(filename, 'w', encoding='utf-8') as f:
1702+
f.write(self.prepare_code())
1703+
return filename
1704+
1705+
def test_script(self):
1706+
# __main__ has __spec__ set to None.
1707+
with os_helper.temp_dir() as dirname:
1708+
filename = self.make_script(dirname)
1709+
rc, out, err = assert_python_ok(filename)
1710+
self.check(err)
1711+
1712+
def test_module(self):
1713+
# __main__ has __spec__ of the module executed with -m.
1714+
with os_helper.temp_dir() as dirname:
1715+
self.make_script(dirname)
1716+
rc, out, err = assert_python_ok('-m', 'spam', PYTHONPATH=dirname)
1717+
self.check(err)
1718+
1719+
def test_command(self):
1720+
# __main__ has the built-in importer as a loader.
1721+
rc, out, err = assert_python_ok('-c', self.prepare_code())
1722+
self.check(err)
1723+
1724+
class CWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase):
1725+
module = c_warnings
1726+
1727+
class PyWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase):
1728+
module = py_warnings
1729+
1730+
16781731
class FinalizationTest(unittest.TestCase):
16791732
def test_finalization(self):
16801733
# 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
@@ -1200,12 +1200,33 @@ get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno
12001200
return NULL;
12011201
}
12021202

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

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

0 commit comments

Comments
 (0)