Skip to content

[3.7] bpo-33509: Fix _warnings for module_globals=None (GH-6833) #6870

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 15, 2018
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
19 changes: 19 additions & 0 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,25 @@ def test_once(self):
42)
self.assertEqual(len(w), 0)

def test_module_globals(self):
with original_warnings.catch_warnings(record=True,
module=self.module) as w:
# bpo-33509: module_globals=None must not crash
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals=None)
self.assertEqual(len(w), 1)

# Invalid module_globals type
with self.assertRaises(TypeError):
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals=True)
self.assertEqual(len(w), 1)

# Empty module_globals
self.module.warn_explicit('msg', UserWarning, "filename", 42,
module_globals={})
self.assertEqual(len(w), 2)

def test_inheritance(self):
with original_warnings.catch_warnings(module=self.module) as w:
self.module.resetwarnings()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix module_globals parameter of warnings.warn_explicit(): don't crash if
module_globals is not a dict.
9 changes: 8 additions & 1 deletion Python/_warnings.c
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,14 @@ warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
&registry, &module_globals, &sourceobj))
return NULL;

if (module_globals) {
if (module_globals && module_globals != Py_None) {
if (!PyDict_Check(module_globals)) {
PyErr_Format(PyExc_TypeError,
"module_globals must be a dict, not '%.200s'",
Py_TYPE(module_globals)->tp_name);
return NULL;
}

source_line = get_source_line(module_globals, lineno);
if (source_line == NULL && PyErr_Occurred()) {
return NULL;
Expand Down