Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Lib/test/test_capi/test_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -2263,6 +2263,44 @@ def testfunc(n):
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)

def test_format_simple_narrows_to_str(self):
def testfunc(n):
x = []
for _ in range(n):
v = 42
s = f"{v}"
t = "hello" + s
x.append(t)
return x

res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
self.assertEqual(res, ["hello42"] * TIER2_THRESHOLD)
self.assertIsNotNone(ex)
uops = get_opnames(ex)

self.assertIn("_FORMAT_SIMPLE", uops)
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)

def test_format_with_spec_narrows_to_str(self):
def testfunc(n):
x = []
for _ in range(n):
v = 3.14
s = f"{v:.2f}"
t = "pi=" + s
x.append(t)
return x

res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
self.assertEqual(res, ["pi=3.14"] * TIER2_THRESHOLD)
self.assertIsNotNone(ex)
uops = get_opnames(ex)

self.assertIn("_FORMAT_WITH_SPEC", uops)
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 Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Allow the JIT to remove unicode guards after ``_FORMAT_SIMPLE`` and
``_FORMAT_WITH_SPEC`` by setting the return type to string.
8 changes: 8 additions & 0 deletions Python/optimizer_bytecodes.c
Original file line number Diff line number Diff line change
Expand Up @@ -1551,6 +1551,14 @@ dummy_func(void) {
set = sym_new_type(ctx, &PySet_Type);
}

op(_FORMAT_SIMPLE, (value -- res)) {
res = sym_new_type(ctx, &PyUnicode_Type);
}

op(_FORMAT_WITH_SPEC, (value, fmt_spec -- res)) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This can return a subclass, e.g.

class my(str):
    def __format__(self, spec):
        return self
m=my('aap')
type(f'{m}')

Does the sym_new_type(ctx, &PyUnicode_Type); not guarantee we have an exact type?

res = sym_new_type(ctx, &PyUnicode_Type);
}

op(_SET_UPDATE, (set, unused[oparg-1], iterable -- set, unused[oparg-1], i)) {
(void)set;
i = iterable;
Expand Down
4 changes: 2 additions & 2 deletions Python/optimizer_cases.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading