Skip to content

Commit b056562

Browse files
authored
bpo-33509: Fix _warnings for module_globals=None (#6833)
Don't crash on warnings.warn_explicit() if module_globals is not a dict.
1 parent 8709b23 commit b056562

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

Lib/test/test_warnings/__init__.py

+19
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,25 @@ def test_once(self):
218218
42)
219219
self.assertEqual(len(w), 0)
220220

221+
def test_module_globals(self):
222+
with original_warnings.catch_warnings(record=True,
223+
module=self.module) as w:
224+
# bpo-33509: module_globals=None must not crash
225+
self.module.warn_explicit('msg', UserWarning, "filename", 42,
226+
module_globals=None)
227+
self.assertEqual(len(w), 1)
228+
229+
# Invalid module_globals type
230+
with self.assertRaises(TypeError):
231+
self.module.warn_explicit('msg', UserWarning, "filename", 42,
232+
module_globals=True)
233+
self.assertEqual(len(w), 1)
234+
235+
# Empty module_globals
236+
self.module.warn_explicit('msg', UserWarning, "filename", 42,
237+
module_globals={})
238+
self.assertEqual(len(w), 2)
239+
221240
def test_inheritance(self):
222241
with original_warnings.catch_warnings(module=self.module) as w:
223242
self.module.resetwarnings()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix module_globals parameter of warnings.warn_explicit(): don't crash if
2+
module_globals is not a dict.

Python/_warnings.c

+8-1
Original file line numberDiff line numberDiff line change
@@ -951,7 +951,14 @@ warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
951951
&registry, &module_globals, &sourceobj))
952952
return NULL;
953953

954-
if (module_globals) {
954+
if (module_globals && module_globals != Py_None) {
955+
if (!PyDict_Check(module_globals)) {
956+
PyErr_Format(PyExc_TypeError,
957+
"module_globals must be a dict, not '%.200s'",
958+
Py_TYPE(module_globals)->tp_name);
959+
return NULL;
960+
}
961+
955962
source_line = get_source_line(module_globals, lineno);
956963
if (source_line == NULL && PyErr_Occurred()) {
957964
return NULL;

0 commit comments

Comments
 (0)