Skip to content

Commit c1b9a83

Browse files
committed
GH-131798: Narrow the return type of _FORMAT_SIMPLE and _FORMAT_WITH_SPEC to str
1 parent afd8113 commit c1b9a83

File tree

4 files changed

+50
-2
lines changed

4 files changed

+50
-2
lines changed

Lib/test/test_capi/test_opt.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2263,6 +2263,44 @@ def testfunc(n):
22632263
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
22642264
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)
22652265

2266+
def test_format_simple_narrows_to_str(self):
2267+
def testfunc(n):
2268+
x = []
2269+
for _ in range(n):
2270+
v = 42
2271+
s = f"{v}"
2272+
t = "hello" + s
2273+
x.append(t)
2274+
return x
2275+
2276+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
2277+
self.assertEqual(res, ["hello42"] * TIER2_THRESHOLD)
2278+
self.assertIsNotNone(ex)
2279+
uops = get_opnames(ex)
2280+
2281+
self.assertIn("_FORMAT_SIMPLE", uops)
2282+
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
2283+
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)
2284+
2285+
def test_format_with_spec_narrows_to_str(self):
2286+
def testfunc(n):
2287+
x = []
2288+
for _ in range(n):
2289+
v = 3.14
2290+
s = f"{v:.2f}"
2291+
t = "pi=" + s
2292+
x.append(t)
2293+
return x
2294+
2295+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
2296+
self.assertEqual(res, ["pi=3.14"] * TIER2_THRESHOLD)
2297+
self.assertIsNotNone(ex)
2298+
uops = get_opnames(ex)
2299+
2300+
self.assertIn("_FORMAT_WITH_SPEC", uops)
2301+
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
2302+
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)
2303+
22662304
def test_binary_op_subscr_str_int(self):
22672305
def testfunc(n):
22682306
x = 0
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Allow the JIT to remove unicode guards after ``_FORMAT_SIMPLE`` and
2+
``_FORMAT_WITH_SPEC`` by setting the return type to string.

Python/optimizer_bytecodes.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1551,6 +1551,14 @@ dummy_func(void) {
15511551
set = sym_new_type(ctx, &PySet_Type);
15521552
}
15531553

1554+
op(_FORMAT_SIMPLE, (value -- res)) {
1555+
res = sym_new_type(ctx, &PyUnicode_Type);
1556+
}
1557+
1558+
op(_FORMAT_WITH_SPEC, (value, fmt_spec -- res)) {
1559+
res = sym_new_type(ctx, &PyUnicode_Type);
1560+
}
1561+
15541562
op(_SET_UPDATE, (set, unused[oparg-1], iterable -- set, unused[oparg-1], i)) {
15551563
(void)set;
15561564
i = iterable;

Python/optimizer_cases.c.h

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

0 commit comments

Comments
 (0)