diff --git a/Lib/test/test_code.py b/Lib/test/test_code.py index 19fa387cd7b271..fac7e9148f1502 100644 --- a/Lib/test/test_code.py +++ b/Lib/test/test_code.py @@ -1164,6 +1164,18 @@ def test_stateless(self): with self.assertRaises(Exception): _testinternalcapi.verify_stateless_code(func) + def test_code_richcompare_raise_exception(self): + class BadStr(str): + def __eq__(self, _): + raise RuntimeError("Poison!") + + __hash__ = str.__hash__ + + c1 = compile("pass", "test", "exec") + c2 = c1.replace(co_name=BadStr("poison")) + c3 = compile("pass", "poison", "exec") + with self.assertRaises(RuntimeError): + c2 == c3 def isinterned(s): return s is sys.intern(('_' + s + '_')[1:-1]) diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-20-12-26-24.gh-issue-146199.vV8V9s.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-03-20-12-26-24.gh-issue-146199.vV8V9s.rst new file mode 100644 index 00000000000000..0611a0d6a6d65a --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-03-20-12-26-24.gh-issue-146199.vV8V9s.rst @@ -0,0 +1 @@ +Comparison of code objects now handles errors correctly. diff --git a/Objects/codeobject.c b/Objects/codeobject.c index fbf0985e9050dd..e2ea0e1a661ee4 100644 --- a/Objects/codeobject.c +++ b/Objects/codeobject.c @@ -2606,7 +2606,7 @@ code_richcompare(PyObject *self, PyObject *other, int op) cp = (PyCodeObject *)other; eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); - if (!eq) goto unequal; + if (eq <= 0) goto unequal; eq = co->co_argcount == cp->co_argcount; if (!eq) goto unequal; eq = co->co_posonlyargcount == cp->co_posonlyargcount;