From de9e4dc2461f1d8a05a830dce3ad44e895deaf25 Mon Sep 17 00:00:00 2001 From: Irit Katriel <1055913+iritkatriel@users.noreply.github.com> Date: Sat, 27 Nov 2021 22:00:10 +0000 Subject: [PATCH] bpo-45614: Fix traceback display for exceptions with invalid module name (GH-29726) (cherry picked from commit 4dfae6f38e1720ddafcdd68043e476ecb41cb4d5) --- Lib/test/test_traceback.py | 11 +++++++++++ Lib/traceback.py | 2 ++ .../2021-11-23-12-06-41.bpo-45614.fIekgI.rst | 1 + Python/pythonrun.c | 2 +- 4 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2021-11-23-12-06-41.bpo-45614.fIekgI.rst diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index ba03ce46294c57..18cd4aba24af26 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -785,6 +785,17 @@ def test_message_none(self): err = self.get_report(Exception('')) self.assertIn('Exception\n', err) + def test_exception_modulename_not_unicode(self): + class X(Exception): + def __str__(self): + return "I am X" + + X.__module__ = 42 + + err = self.get_report(X()) + exp = f'.{X.__qualname__}: I am X\n' + self.assertEqual(exp, err) + def test_syntax_error_various_offsets(self): for offset in range(-5, 10): for add in [0, 2]: diff --git a/Lib/traceback.py b/Lib/traceback.py index 901b99476aaf85..d6a010f4157582 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -604,6 +604,8 @@ def format_exception_only(self): stype = self.exc_type.__qualname__ smod = self.exc_type.__module__ if smod not in ("__main__", "builtins"): + if not isinstance(smod, str): + smod = "" stype = smod + '.' + stype if not issubclass(self.exc_type, SyntaxError): diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-11-23-12-06-41.bpo-45614.fIekgI.rst b/Misc/NEWS.d/next/Core and Builtins/2021-11-23-12-06-41.bpo-45614.fIekgI.rst new file mode 100644 index 00000000000000..4255e1885ad67c --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2021-11-23-12-06-41.bpo-45614.fIekgI.rst @@ -0,0 +1 @@ +Fix :mod:`traceback` display for exceptions with invalid module name. \ No newline at end of file diff --git a/Python/pythonrun.c b/Python/pythonrun.c index 5704bcc7589f32..0f1794acec73ae 100644 --- a/Python/pythonrun.c +++ b/Python/pythonrun.c @@ -972,7 +972,7 @@ print_exception(PyObject *f, PyObject *value) { Py_XDECREF(modulename); PyErr_Clear(); - err = PyFile_WriteString("", f); + err = PyFile_WriteString(".", f); } else { if (!_PyUnicode_EqualToASCIIId(modulename, &PyId_builtins))