From ad3708a95fbd64bdf569f43c89089bacb79494ef Mon Sep 17 00:00:00 2001 From: Bhuvansh855 Date: Wed, 8 Jul 2026 23:57:02 +0530 Subject: [PATCH] gh-153354: Fix bool conversion in generated __annotate__ --- Lib/test/test_annotationlib.py | 31 +++++++++++++++++++ ...-07-09-13-28-27.gh-issue-153354.It4Jj_.rst | 2 ++ Python/codegen.c | 1 + 3 files changed, 34 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-07-09-13-28-27.gh-issue-153354.It4Jj_.rst diff --git a/Lib/test/test_annotationlib.py b/Lib/test/test_annotationlib.py index 5087c3ca425f1fc..24ec86ea2063d09 100644 --- a/Lib/test/test_annotationlib.py +++ b/Lib/test/test_annotationlib.py @@ -1713,6 +1713,37 @@ def annotate(format, /): with self.assertRaises(DemoException): annotationlib.call_annotate_function(annotate, format=fmt) + def test_generated_annotate_non_bool_compare_result(self): + class NonBool: + def __gt__(self, other): + return None + + # Function __annotate__ + def func(x: int): + pass + + self.assertEqual( + func.__annotate__(NonBool()), + {"x": int}, + ) + + # Class __annotate__ + class C: + y: int + + self.assertEqual( + C.__annotate__(NonBool()), + {"y": int}, + ) + + # Module __annotate__ + ns = {} + exec("z: int", ns) + + self.assertEqual( + ns["__annotate__"](NonBool()), + {"z": int}, + ) class MetaclassTests(unittest.TestCase): def test_annotated_meta(self): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-09-13-28-27.gh-issue-153354.It4Jj_.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-09-13-28-27.gh-issue-153354.It4Jj_.rst new file mode 100644 index 000000000000000..4cfd4302b3c34d6 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-09-13-28-27.gh-issue-153354.It4Jj_.rst @@ -0,0 +1,2 @@ +Fix a crash in compiler-generated ``__annotate__`` functions when the +annotation format comparison returned a non-boolean result. diff --git a/Python/codegen.c b/Python/codegen.c index 81fecd09a2060d1..605d1bd8d0eac16 100644 --- a/Python/codegen.c +++ b/Python/codegen.c @@ -724,6 +724,7 @@ codegen_setup_annotations_scope(compiler *c, location loc, ADDOP_I(c, loc, LOAD_FAST, 0); ADDOP_LOAD_CONST_NEW(c, loc, value_with_fake_globals); ADDOP_I(c, loc, COMPARE_OP, (Py_GT << 5) | compare_masks[Py_GT]); + ADDOP(c, loc, TO_BOOL); NEW_JUMP_TARGET_LABEL(c, body); ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, body); ADDOP_I(c, loc, LOAD_COMMON_CONSTANT, CONSTANT_NOTIMPLEMENTEDERROR);