Skip to content

Commit 404359d

Browse files
committed
Handle non-unicode __name__, drop unnecessary cast
1 parent cb5ae96 commit 404359d

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

Lib/test/test_exceptions.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2162,6 +2162,15 @@ def raise_custom(name):
21622162
self.assertIs(cm.exception.obj, nameless_mod)
21632163
self.assertEqual(cm.exception.name, "missing4")
21642164

2165+
nameless_mod = ModuleType("broken")
2166+
nameless_mod.__dict__["__name__"] = 10j
2167+
nameless_mod.__getattr__ = raise_with_name
2168+
with self.assertRaises(AttributeError) as cm:
2169+
getattr(nameless_mod, "missing4")
2170+
self.assertEqual(str(cm.exception), "module has no attribute 'missing4'")
2171+
self.assertIs(cm.exception.obj, nameless_mod)
2172+
self.assertEqual(cm.exception.name, "missing4")
2173+
21652174
# Note: name suggestion tests live in `test_traceback`.
21662175

21672176

Objects/exceptions.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2741,16 +2741,17 @@ AttributeError_str(PyObject *op)
27412741
if (PyDict_GetItemRef(mod->md_dict, &_Py_ID(__name__), &modname) < 0) {
27422742
goto error;
27432743
}
2744-
if (modname) {
2744+
if (modname && PyUnicode_Check(modname)) {
27452745
result = PyUnicode_FromFormat("module '%U' has no attribute '%U'",
27462746
modname, name);
27472747
Py_DECREF(modname);
27482748
} else {
2749+
Py_XDECREF(modname);
27492750
result = PyUnicode_FromFormat("module has no attribute '%U'", name);
27502751
}
27512752
} else if (PyType_Check(obj)) {
27522753
result = PyUnicode_FromFormat("type object '%N' has no attribute '%U'",
2753-
_PyType_CAST(obj), name);
2754+
obj, name);
27542755
} else {
27552756
result = PyUnicode_FromFormat("'%T' object has no attribute '%U'",
27562757
obj, name);

0 commit comments

Comments
 (0)