Skip to content

Commit f2eaf17

Browse files
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).
1 parent 350fc64 commit f2eaf17

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

17191719

1720+
class WarnExplicitMainTests(BaseTest):
1721+
# gh-123011: warn_explicit() with module globals of the __main__ module,
1722+
# no matter how it is executed.
1723+
code = ('import warnings\n'
1724+
'warnings.warn_explicit("eggs", UserWarning, "bar", 1,\n'
1725+
' module_globals=globals())\n')
1726+
1727+
def prepare_code(self):
1728+
"""Make the subprocess use the tested implementation."""
1729+
if self.module is py_warnings:
1730+
return ("import sys\n"
1731+
"sys.modules['_warnings'] = None\n") + self.code
1732+
return self.code
1733+
1734+
def check(self, err):
1735+
lines = err.decode().splitlines()
1736+
# Only the Python implementation adds the source line.
1737+
if len(lines) > 1 and lines[1].startswith(' '):
1738+
del lines[1]
1739+
self.assertEqual(lines, ['bar:1: UserWarning: eggs'])
1740+
1741+
def make_script(self, dirname):
1742+
filename = os.path.join(dirname, 'spam.py')
1743+
with open(filename, 'w', encoding='utf-8') as f:
1744+
f.write(self.prepare_code())
1745+
return filename
1746+
1747+
def test_script(self):
1748+
# __main__ has __spec__ set to None.
1749+
with os_helper.temp_dir() as dirname:
1750+
filename = self.make_script(dirname)
1751+
rc, out, err = assert_python_ok(filename)
1752+
self.check(err)
1753+
1754+
def test_module(self):
1755+
# __main__ has __spec__ of the module executed with -m.
1756+
with os_helper.temp_dir() as dirname:
1757+
self.make_script(dirname)
1758+
rc, out, err = assert_python_ok('-m', 'spam', PYTHONPATH=dirname)
1759+
self.check(err)
1760+
1761+
def test_command(self):
1762+
# __main__ has the built-in importer as a loader.
1763+
rc, out, err = assert_python_ok('-c', self.prepare_code())
1764+
self.check(err)
1765+
1766+
class CWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase):
1767+
module = c_warnings
1768+
1769+
class PyWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase):
1770+
module = py_warnings
1771+
1772+
17201773
class FinalizationTest(unittest.TestCase):
17211774
def test_finalization(self):
17221775
# 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)