Skip to content

Commit ef83f33

Browse files
committed
gh-131798: Constant-fold _CONTAINS_OP_DICT for frozendict
1 parent 5ce0fe8 commit ef83f33

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

Lib/test/test_capi/test_opt.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4678,6 +4678,34 @@ def testfunc(n):
46784678
uops = get_opnames(ex)
46794679
self.assertNotIn("_CONTAINS_OP_SET", uops)
46804680

4681+
def test_contains_op_frozendict_const_fold(self):
4682+
def testfunc(n):
4683+
x = 0
4684+
for _ in range(n):
4685+
if 'x' in FROZEN_DICT_CONST:
4686+
x += 1
4687+
return x
4688+
4689+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
4690+
self.assertEqual(res, TIER2_THRESHOLD)
4691+
self.assertIsNotNone(ex)
4692+
uops = get_opnames(ex)
4693+
self.assertNotIn("_CONTAINS_OP_DICT", uops)
4694+
4695+
def test_not_contains_op_frozendict_const_fold(self):
4696+
def testfunc(n):
4697+
x = 0
4698+
for _ in range(n):
4699+
if 'z' not in FROZEN_DICT_CONST:
4700+
x += 1
4701+
return x
4702+
4703+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
4704+
self.assertEqual(res, TIER2_THRESHOLD)
4705+
self.assertIsNotNone(ex)
4706+
uops = get_opnames(ex)
4707+
self.assertNotIn("_CONTAINS_OP_DICT", uops)
4708+
46814709
def test_binary_subscr_list_slice(self):
46824710
def testfunc(n):
46834711
x = 0

Python/optimizer_bytecodes.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,10 @@ dummy_func(void) {
761761
b = sym_new_type(ctx, &PyBool_Type);
762762
l = left;
763763
r = right;
764+
if (sym_is_not_container(left) &&
765+
sym_matches_type(right, &PyFrozenDict_Type)) {
766+
REPLACE_OPCODE_IF_EVALUATES_PURE(left, right, b);
767+
}
764768
}
765769

766770
op(_LOAD_CONST, (-- value)) {

Python/optimizer_cases.c.h

Lines changed: 47 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)