Skip to content

Commit 5b6aa6c

Browse files
authored
bpo-45614: Fix traceback display for exceptions with invalid module name (GH-29726) (GH-29827)
(cherry picked from commit 4dfae6f)
1 parent 209cec8 commit 5b6aa6c

File tree

4 files changed

+15
-1
lines changed

4 files changed

+15
-1
lines changed

Lib/test/test_traceback.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,17 @@ def test_message_none(self):
740740
err = self.get_report(Exception(''))
741741
self.assertIn('Exception\n', err)
742742

743+
def test_exception_modulename_not_unicode(self):
744+
class X(Exception):
745+
def __str__(self):
746+
return "I am X"
747+
748+
X.__module__ = 42
749+
750+
err = self.get_report(X())
751+
exp = f'<unknown>.{X.__qualname__}: I am X\n'
752+
self.assertEqual(exp, err)
753+
743754
def test_syntax_error_various_offsets(self):
744755
for offset in range(-5, 10):
745756
for add in [0, 2]:

Lib/traceback.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,8 @@ def format_exception_only(self):
574574
stype = self.exc_type.__qualname__
575575
smod = self.exc_type.__module__
576576
if smod not in ("__main__", "builtins"):
577+
if not isinstance(smod, str):
578+
smod = "<unknown>"
577579
stype = smod + '.' + stype
578580

579581
if not issubclass(self.exc_type, SyntaxError):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :mod:`traceback` display for exceptions with invalid module name.

Python/pythonrun.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -903,7 +903,7 @@ print_exception(PyObject *f, PyObject *value)
903903
{
904904
Py_XDECREF(modulename);
905905
PyErr_Clear();
906-
err = PyFile_WriteString("<unknown>", f);
906+
err = PyFile_WriteString("<unknown>.", f);
907907
}
908908
else {
909909
if (!_PyUnicode_EqualToASCIIId(modulename, &PyId_builtins))

0 commit comments

Comments
 (0)