[Python-checkins] bpo-31566: Fix an assertion failure in _warnings.warn() in case of a bad __name__ global. (#3717)

Serhiy Storchaka webhook-mailer at python.org
Sun Sep 24 14:28:45 EDT 2017


https://github.com/python/cpython/commit/5d3e80021ab33360191eb0fbff34e0246c913884
commit: 5d3e80021ab33360191eb0fbff34e0246c913884
branch: master
author: Oren Milman <orenmn at gmail.com>
committer: Serhiy Storchaka <storchaka at gmail.com>
date: 2017-09-24T21:28:42+03:00
summary:

bpo-31566: Fix an assertion failure in _warnings.warn() in case of a bad __name__ global. (#3717)

files:
A Misc/NEWS.d/next/Core and Builtins/2017-09-24-09-57-04.bpo-31566.OxwINs.rst
M Lib/test/test_warnings/__init__.py
M Python/_warnings.c

diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py
index f27ee6ef681..e007dc7e39e 100644
--- a/Lib/test/test_warnings/__init__.py
+++ b/Lib/test/test_warnings/__init__.py
@@ -856,6 +856,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):
 
diff --git a/Misc/NEWS.d/next/Core and Builtins/2017-09-24-09-57-04.bpo-31566.OxwINs.rst b/Misc/NEWS.d/next/Core and Builtins/2017-09-24-09-57-04.bpo-31566.OxwINs.rst
new file mode 100644
index 00000000000..d3ccfd7a242
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2017-09-24-09-57-04.bpo-31566.OxwINs.rst	
@@ -0,0 +1,2 @@
+Fix an assertion failure in `_warnings.warn()` in case of a bad
+``__name__`` global. Patch by Oren Milman.
diff --git a/Python/_warnings.c b/Python/_warnings.c
index f56e92d2c1b..4ea9fce47cf 100644
--- a/Python/_warnings.c
+++ b/Python/_warnings.c
@@ -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__");



More information about the Python-checkins mailing list