8000 bpo-45614: Fix traceback display for exceptions with invalid module n… · python/cpython@4dfae6f · GitHub
[go: up one dir, main page]

Skip to content

Commit 4dfae6f

Browse files
authored
bpo-45614: Fix traceback display for exceptions with invalid module name (GH-29726)
1 parent e71c12e commit 4dfae6f

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
@@ -1254,6 +1254,17 @@ def __str__(self):
12541254
exp = "%s: %s\n" % (str_name, str_value)
12551255
self.assertEqual(exp, err)
12561256

1257+
def test_exception_modulename_not_unicode(self):
1258+
class X(Exception):
1259+
def __str__(self):
1260+
return "I am X"
1261+
1262+
X.__module__ = 42
1263+
1264+
err = self.get_report(X())
1265+
exp = f'<unknown>.{X.__qualname__}: I am X\n'
1266+
self.assertEqual(exp, err)
1267+
12571268
def test_exception_bad__str__(self):
12581269
class X(Exception):
12591270
def __str__(self):

Lib/traceback.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,8 @@ def format_exception_only(self):
808808
stype = self.exc_type.__qualname__
809809
smod = self.exc_type.__module__
810810
if smod not in ("__main__", "builtins"):
811+
if not isinstance(smod, str):
812+
smod = "<unknown>"
811813
stype = smod + '.' + stype
812814

813815
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
@@ -1022,7 +1022,7 @@ print_exception(struct exception_print_context *ctx, PyObject *value)
10221022
{
10231023
Py_XDECREF(modulename);
10241024
PyErr_Clear();
1025-
err = PyFile_WriteString("<unknown>", f);
1025+
err = PyFile_WriteString("<unknown>.", f);
10261026
}
10271027
else {
10281028
if (!_PyUnicode_EqualToASCIIId(modulename, &PyId_builtins) &&

0 commit comments

Comments
 (0)
0