Constant-fold f-strings with constant fields in the CFG optimizer
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Feature or enhancement
Proposal:
The flowgraph optimizer folds constant expressions in most positions (binary/unary ops, tuples of constants, in against literal collections), but f-strings whose fields are all constants are left unfolded:
>>> import dis
>>> dis.dis(lambda: f'{1}{2}')
RESUME 0
LOAD_SMALL_INT 1
FORMAT_SIMPLE
LOAD_SMALL_INT 2
FORMAT_SIMPLE
BUILD_STRING 2
RETURN_VALUE
This could compile to a single LOAD_CONST '12', the same way '1' + '2' already does.
The transformation is safe under a narrow guard:
FORMAT_SIMPLEon an operand that is an exactstr,int,floatorboolconstant is pure and calls no user code (subclasses can override__format__/__str__, so exact-type checks are required).FORMAT_WITH_SPECwith a constant spec on those exact types is pure for the same reason, though it could be left to a follow-up.BUILD_STRINGover constant strings is pure.
Conversion functions (!r, !s, !a) lower to intrinsics before FORMAT_SIMPLE, so f'{1!r}' is out of scope unless the intrinsic is also handled; the initial change can simply not match those sequences.
Constant fields do appear in real code — mixed f-strings like f'{HEADER}{x}' gain partially (the constant fields fold, shrinking BUILD_STRING's operand count), and fully-constant f-strings show up in generated code and in string-building via comprehensions.
The natural place is a fold_format_simple alongside fold_tuple_of_constants in Python/flowgraph.c, using the existing get_const_loading_instrs / instr_make_load_const helpers.
gh-77273 covered the opcode-level inefficiency of f-string formatting and was resolved by the FORMAT_SIMPLE/FORMAT_WITH_SPEC redesign; this proposal is about folding the constant cases of those opcodes, which is not currently done anywhere in the compiler.
With a prototype of the fold, a fully-constant f-string costs the same as the equivalent string literal (~34 ns/call instead of ~1770 ns/call on a debug free-threaded build — I'll post release-build pyperf numbers on the PR). I have a patch ready and will follow up with it.
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
Linked PRs
- gh-154911
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Python/flowgraph.c 中 fold_tuple_of_constants 旁边开始,并检查 get_const_loading_instrs 和 instr_make_load_const。验证优化器能够处理符合条件的常量 FORMAT_SIMPLE 和 BUILD_STRING 序列,同时保持转换和非精确类型不变,然后将生成的字节码和性能与链接的 PR gh-154911 进行比较。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- compilers
- Issue 类型
- 功能
- 难度
- 3/5
- 预计耗时
- 1-2 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100