Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,16 @@ def test_issue31416(self):
self.assertRaises(TypeError):
wmod.warn_explicit('foo', Warning, 'bar', 1)

@support.cpython_only
def test_issue31566(self):
# warn() shouldn't cause an assertion failure in case of a bad
# __name__ global.
with original_warnings.catch_warnings(module=self.module):
self.module.filterwarnings('error', category=UserWarning)
with support.swap_item(globals(), '__name__', b'foo'), \
support.swap_item(globals(), '__file__', None):
self.assertRaises(UserWarning, self.module.warn, 'bar')


class WarningsDisplayTests(BaseTest):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix an assertion failure in `_warnings.warn()` in case of a bad
``__name__`` global. Patch by Oren Milman.
7 changes: 4 additions & 3 deletions Python/_warnings.c
Original file line number Diff line number Diff line change
Expand Up @@ -684,13 +684,14 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,

/* Setup module. */
*module = PyDict_GetItemString(globals, "__name__");
if (*module == NULL) {
if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
Py_INCREF(*module);
}
else {
*module = PyUnicode_FromString("<string>");
if (*module == NULL)
goto handle_error;
}
else
Py_INCREF(*module);

/* Setup filename. */
*filename = PyDict_GetItemString(globals, "__file__");
Expand Down