Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Prev Previous commit
Next Next commit
add tests
  • Loading branch information
chris-eibl committed Jan 4, 2026
commit c56ca350eef260680a3f9ad3080a61044774534f
40 changes: 40 additions & 0 deletions Lib/test/test_capi/test_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1904,6 +1904,26 @@ def testfunc(n):
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)

def test_binary_subcsr_ustr_int_narrows_to_str(self):
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought of paramterizing test_binary_subcsr_str_int_narrows_to_str and test_binary_op_subscr_str_int to get rid of duplication, but it resulted in worse readable code, because the input and the expectations have to be varied ...

def testfunc(n):
x = []
s = "바이트코f드_특수화"
for _ in range(n):
y = s[4] # _BINARY_OP_SUBSCR_USTR_INT
z = "bar" + y # (_GUARD_TOS_UNICODE) + _BINARY_OP_ADD_UNICODE
x.append(z)
return x

res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
self.assertEqual(res, ["barf"] * TIER2_THRESHOLD)
self.assertIsNotNone(ex)
uops = get_opnames(ex)
self.assertIn("_BINARY_OP_SUBSCR_USTR_INT", uops)
# _BINARY_OP_SUBSCR_USTR_INT narrows the result to 'str' so
# the unicode guard before _BINARY_OP_ADD_UNICODE is removed.
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)

def test_binary_op_subscr_str_int(self):
def testfunc(n):
x = 0
Expand All @@ -1924,6 +1944,26 @@ def testfunc(n):
self.assertLessEqual(count_ops(ex, "_POP_TOP"), 2)
self.assertLessEqual(count_ops(ex, "_POP_TOP_INT"), 1)

def test_binary_op_subscr_ustr_int(self):
Comment thread
chris-eibl marked this conversation as resolved.
def testfunc(n):
x = 0
s = "hello바"
for _ in range(n):
c = s[1] # _BINARY_OP_SUBSCR_USTR_INT
if c == 'e':
x += 1
return x

res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
self.assertEqual(res, TIER2_THRESHOLD)
self.assertIsNotNone(ex)
uops = get_opnames(ex)
self.assertIn("_BINARY_OP_SUBSCR_USTR_INT", uops)
self.assertIn("_COMPARE_OP_STR", uops)
self.assertIn("_POP_TOP_NOP", uops)
self.assertLessEqual(count_ops(ex, "_POP_TOP"), 2)
self.assertLessEqual(count_ops(ex, "_POP_TOP_INT"), 1)

def test_call_type_1_guards_removed(self):
def testfunc(n):
x = 0
Expand Down
1 change: 1 addition & 0 deletions Lib/test/test_opcache.py
Original file line number Diff line number Diff line change
Expand Up @@ -1792,6 +1792,7 @@ def binary_subscr_str_int_non_compact():
self.assertEqual(a[idx], expected)

binary_subscr_str_int_non_compact()
self.assert_specialized(binary_subscr_str_int_non_compact, "BINARY_OP_SUBSCR_USTR_INT")
self.assert_no_opcode(binary_subscr_str_int_non_compact, "BINARY_OP_SUBSCR_STR_INT")

def binary_subscr_getitems():
Expand Down