Skip to content

Commit 4d2cc3e

Browse files
authored
bpo-45614: Fix traceback display for exceptions with invalid module name (GH-29726) (GH-29826)
(cherry picked from commit 4dfae6f)
1 parent 305236e commit 4d2cc3e

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
@@ -785,6 +785,17 @@ def test_message_none(self):
785785
err = self.get_report(Exception(''))
786786
self.assertIn('Exception\n', err)
787787

788+
def test_exception_modulename_not_unicode(self):
789+
class X(Exception):
790+
def __str__(self):
791+
return "I am X"
792+
793+
X.__module__ = 42
794+
795+
err = self.get_report(X())
796+
exp = f'<unknown>.{X.__qualname__}: I am X\n'
797+
self.assertEqual(exp, err)
798+
788799
def test_syntax_error_various_offsets(self):
789800
for offset in range(-5, 10):
790801
for add in [0, 2]:

Lib/traceback.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,8 @@ def format_exception_only(self):
604604
stype = self.exc_type.__qualname__
605605
smod = self.exc_type.__module__
606606
if smod not in ("__main__", "builtins"):
607+
if not isinstance(smod, str):
608+
smod = "<unknown>"
607609
stype = smod + '.' + stype
608610

609611
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
@@ -972,7 +972,7 @@ print_exception(PyObject *f, PyObject *value)
972972
{
973973
Py_XDECREF(modulename);
974974
PyErr_Clear();
975-
err = PyFile_WriteString("<unknown>", f);
975+
err = PyFile_WriteString("<unknown>.", f);
976976
}
977977
else {
978978
if (!_PyUnicode_EqualToASCIIId(modulename, &PyId_builtins))

0 commit comments

Comments
 (0)