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
1 change: 1 addition & 0 deletions Include/internal/pycore_optimizer.h
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,7 @@ extern JitOptRef _Py_uop_sym_new_type(

extern JitOptRef _Py_uop_sym_new_const(JitOptContext *ctx, PyObject *const_val);
extern JitOptRef _Py_uop_sym_new_const_steal(JitOptContext *ctx, PyObject *const_val);
extern bool _Py_uop_sym_is_safe_type(JitOptRef sym);
bool _Py_uop_sym_is_safe_const(JitOptContext *ctx, JitOptRef sym);
_PyStackRef _Py_uop_sym_get_const_as_stackref(JitOptContext *ctx, JitOptRef sym);
extern JitOptRef _Py_uop_sym_new_null(JitOptContext *ctx);
Expand Down
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`` when the input type is a known built-in type.
1 change: 1 addition & 0 deletions Python/optimizer_analysis.c
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ add_op(JitOptContext *ctx, _PyUOpInstruction *this_instr,
/* Shortened forms for convenience, used in optimizer_bytecodes.c */
#define sym_is_not_null _Py_uop_sym_is_not_null
#define sym_is_const _Py_uop_sym_is_const
#define sym_is_safe_type _Py_uop_sym_is_safe_type
#define sym_is_safe_const _Py_uop_sym_is_safe_const
#define sym_get_const _Py_uop_sym_get_const
#define sym_new_const_steal _Py_uop_sym_new_const_steal
Expand Down
16 changes: 16 additions & 0 deletions Python/optimizer_bytecodes.c
Original file line number Diff line number Diff line change
Expand Up @@ -1551,6 +1551,22 @@ dummy_func(void) {
set = sym_new_type(ctx, &PySet_Type);
}

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

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch! I oversimplified this. Narrowing type for format isn't as straightforward as I thought.

That said, I'm curious why FORMAT_SIMPLE needs to preserve str subclasses. Had a look through the git history it's been this way since 2015, and seems not a deliberate type-preservation contract.

Current behaviour is already inconsistent:

class my(str):
    def __format__(self, spec):
        return self

m = my('aap')
type('{}'.format(m))   # <class 'my'>
type('x{}'.format(m))  # <class 'str'>
type(f'{m}')           # <class 'my'>
type(f'x{m}')          # <class 'str'>

Multi-piece concatenation already strips it (both _PyUnicodeWriter in str.format and BUILD_STRING in f-strings create exact str).

If FORMAT_SIMPLE normalised to exact str, this inconsistency goes away and type narrowing becomes unconditionally correct. Would that be a reasonable change, or is there a reason to preserve str subclass identity through formatting that I'm missing?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Huh that's kinda scary. The semantics look a little strange, so maybe we should leave this alone for now?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fair enough. I just noticed the inconsistency and thought it was worth raising.

For the narrowing itself: we could do conditional narrowing for input types where we can prove __format__ returns exact str (e.g. int, float). But honestly it feels not pythonic to hardcode a list of "safe" types for a uop that's less then 0.1%. I'd prefer just closing this PR unless you think it's worth keeping with that approach?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Actually we already have something like that called sym_is_safe_type, you can use that

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I couldn't find sym_is_safe_type anywhere. The closest thing I can see is sym_is_safe_const, but that checks for known constant values rather than types. Have I overlooked something?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Oh yeah sorry that's the one! Just factor out the type checks in _Py_uop_sym_is_safe_const into another function and use that in this case, I think that's fine!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. How does it look now?

if (sym_is_safe_type(value)) {
res = sym_new_type(ctx, &PyUnicode_Type);
} else {
res = sym_new_not_null(ctx);
}
}

op(_SET_UPDATE, (set, unused[oparg-1], iterable -- set, unused[oparg-1], i)) {
(void)set;
i = iterable;
Expand Down
16 changes: 14 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.

30 changes: 25 additions & 5 deletions Python/optimizer_symbols.c
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,30 @@ _Py_uop_sym_get_const_as_stackref(JitOptContext *ctx, JitOptRef sym)
return PyStackRef_FromPyObjectBorrow(const_val);
}

static bool
is_safe_builtin_type(PyTypeObject *typ)
{
return (typ == &PyUnicode_Type) ||
(typ == &PyFloat_Type) ||
(typ == &_PyNone_Type) ||
(typ == &PyBool_Type) ||
(typ == &PyFrozenDict_Type);
}

/*
Indicates whether the type is a known built-in type
that is safe to narrow.
*/
bool
_Py_uop_sym_is_safe_type(JitOptRef sym)
{
PyTypeObject *typ = _Py_uop_sym_get_type(sym);
if (typ == NULL) {
return false;
}
return (typ == &PyLong_Type) || is_safe_builtin_type(typ);
}

/*
Indicates whether the constant is safe to constant evaluate
(without side effects).
Expand All @@ -279,11 +303,7 @@ _Py_uop_sym_is_safe_const(JitOptContext *ctx, JitOptRef sym)
return true;
}
PyTypeObject *typ = Py_TYPE(const_val);
return (typ == &PyUnicode_Type) ||
(typ == &PyFloat_Type) ||
(typ == &_PyNone_Type) ||
(typ == &PyBool_Type) ||
(typ == &PyFrozenDict_Type);
return is_safe_builtin_type(typ);
}

void
Expand Down
Loading