Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5d3e800

Browse files
orenmnserhiy-storchaka
authored andcommitted
bpo-31566: Fix an assertion failure in _warnings.warn() in case of a bad __name__ global. (#3717)
1 parent 91fb0af commit 5d3e800

3 files changed

Lines changed: 16 additions & 3 deletions

File tree

Lib/test/test_warnings/__init__.py

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

859+
@support.cpython_only
860+
def test_issue31566(self):
861+
# warn() shouldn't cause an assertion failure in case of a bad
862+
# __name__ global.
863+
with original_warnings.catch_warnings(module=self.module):
864+
self.module.filterwarnings('error', category=UserWarning)
865+
with support.swap_item(globals(), '__name__', b'foo'), \
866+
support.swap_item(globals(), '__file__', None):
867+
self.assertRaises(UserWarning, self.module.warn, 'bar')
868+
859869

860870
class WarningsDisplayTests(BaseTest):
861871

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
@@ -684,13 +684,14 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
684684

685685
/* Setup module. */
686686
*module = PyDict_GetItemString(globals, "__name__");
687-
if (*module == NULL) {
687+
if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
688+
Py_INCREF(*module);
689+
}
690+
else {
688691
*module = PyUnicode_FromString("<string>");
689692
if (*module == NULL)
690693
goto handle_error;
691694
}
692-
else
693-
Py_INCREF(*module);
694695

695696
/* Setup filename. */
696697
*filename = PyDict_GetItemString(globals, "__file__");

0 commit comments

Comments
 (0)