Skip to content

Commit 415cc1f

Browse files
miss-islingtonserhiy-storchaka
authored andcommitted
[3.6] bpo-31566: Fix an assertion failure in _warnings.warn() in case of a bad __name__ global. (GH-3717) (#3730)
(cherry picked from commit 5d3e800)
1 parent ce418bf commit 415cc1f

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

‎Lib/test/test_warnings/__init__.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,16 @@ def test_issue31416(self):
820820
self.assertRaises(TypeError):
821821
wmod.warn_explicit('foo', Warning, 'bar', 1)
822822

823+
@support.cpython_only
824+
def test_issue31566(self):
825+
# warn() shouldn't cause an assertion failure in case of a bad
826+
# __name__ global.
827+
with original_warnings.catch_warnings(module=self.module):
828+
self.module.filterwarnings('error', category=UserWarning)
829+
with support.swap_item(globals(), '__name__', b'foo'), \
830+
support.swap_item(globals(), '__file__', None):
831+
self.assertRaises(UserWarning, self.module.warn, 'bar')
832+
823833

824834
class WarningsDisplayTests(BaseTest):
825835

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix an assertion failure in `_warnings.warn()` in case of a bad
2+
``__name__`` global. Patch by Oren Milman.

‎Python/_warnings.c‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -694,13 +694,14 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
694694

695695
/* Setup module. */
696696
*module = PyDict_GetItemString(globals, "__name__");
697-
if (*module == NULL) {
697+
if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
698+
Py_INCREF(*module);
699+
}
700+
else {
698701
*module = PyUnicode_FromString("<string>");
699702
if (*module == NULL)
700703
goto handle_error;
701704
}
702-
else
703-
Py_INCREF(*module);
704705

705706
/* Setup filename. */
706707
*filename = PyDict_GetItemString(globals, "__file__");

0 commit comments

Comments
 (0)