Skip to content

Commit 7d3fca4

Browse files
authored
gh-153354: Fix bool conversion in generated __annotate__ (#153360)
1 parent 0f1d4a7 commit 7d3fca4

3 files changed

Lines changed: 34 additions & 0 deletions

File tree

‎Lib/test/test_annotationlib.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1720,6 +1720,37 @@ def annotate(format, /):
17201720
with self.assertRaises(DemoException):
17211721
annotationlib.call_annotate_function(annotate, format=fmt)
17221722

1723+
def test_generated_annotate_non_bool_compare_result(self):
1724+
class NonBool(int):
1725+
def __gt__(self, other):
1726+
return None
1727+
1728+
# Function __annotate__
1729+
def func(x: int):
1730+
pass
1731+
1732+
self.assertEqual(
1733+
func.__annotate__(NonBool(1)),
1734+
{"x": int},
1735+
)
1736+
1737+
# Class __annotate__
1738+
class C:
1739+
y: int
1740+
1741+
self.assertEqual(
1742+
C.__annotate__(NonBool(1)),
1743+
{"y": int},
1744+
)
1745+
1746+
# Module __annotate__
1747+
ns = {}
1748+
exec("z: int", ns)
1749+
1750+
self.assertEqual(
1751+
ns["__annotate__"](NonBool(1)),
1752+
{"z": int},
1753+
)
17231754

17241755
class MetaclassTests(unittest.TestCase):
17251756
def test_annotated_meta(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash in compiler-generated ``__annotate__`` functions when the
2+
annotation format comparison returned a non-boolean result.

‎Python/codegen.c‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,7 @@ codegen_emit_annotations_prologue(compiler *c, location loc)
729729
ADDOP_I(c, loc, LOAD_FAST, 0);
730730
ADDOP_LOAD_CONST_NEW(c, loc, value_with_fake_globals);
731731
ADDOP_I(c, loc, COMPARE_OP, (Py_GT << 5) | compare_masks[Py_GT]);
732+
ADDOP(c, loc, TO_BOOL);
732733
NEW_JUMP_TARGET_LABEL(c, body);
733734
ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, body);
734735
ADDOP_I(c, loc, LOAD_COMMON_CONSTANT, CONSTANT_NOTIMPLEMENTEDERROR);

0 commit comments

Comments
 (0)