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
4 changes: 2 additions & 2 deletions mypyc/irbuild/format_str_tokenizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def generate_format_ops(specifiers: list[ConversionSpecifier]) -> list[FormatOp]
format_ops = []
for spec in specifiers:
# TODO: Match specifiers instead of using whole_seq
if spec.whole_seq == "%s" or spec.whole_seq == "{:{}}":
if spec.whole_seq == "%s" or spec.whole_seq in ("{:{}}", ":s"):
format_op = FormatOp.STR
elif spec.whole_seq == "%d":
elif spec.whole_seq in ("%d", ":d"):
format_op = FormatOp.INT
elif spec.whole_seq == "%b":
format_op = FormatOp.BYTES
Expand Down
23 changes: 23 additions & 0 deletions mypyc/test-data/irbuild-constant-fold.test
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,16 @@ L0:
from typing import Any, Final

FMT: Final = "{} {}"
FMT_D: Final = "{:d} {:s}"
FMT_S: Final = "{:s} {:s}"

def f() -> str:
return FMT.format(400 + 20, "roll" + "up")
def g() -> str:
return FMT_D.format(400 + 20, "roll" + "up")
def h() -> str:
return FMT_S.format(400 + 20, "roll" + "up")
Copy link
Collaborator

Choose a reason for hiding this comment

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

In Python, {:s} appears to only support str values. There is no implicit conversion to strings:

>>> '{:s}'.format(2)
Traceback (most recent call last):
  File "<python-input-7>", line 1, in <module>
    '{:s}'.format(2)
    ~~~~~~~~~~~~~^^^
ValueError: Unknown format code 's' for object of type 'int'

I think we should have similar checks to support :s in a compatible way, or apply the optimization if the static type of the corresponding operand is builtins.str perhaps.


[out]
def f():
r0, r1, r2, r3 :: str
Expand All @@ -204,6 +211,22 @@ L0:
r2 = ' '
r3 = CPyStr_Build(3, r0, r2, r1)
return r3
def g():
r0, r1, r2, r3 :: str
L0:
r0 = '420'
r1 = 'rollup'
r2 = ' '
r3 = CPyStr_Build(3, r0, r2, r1)
return r3
def h():
r0, r1, r2, r3 :: str
L0:
r0 = CPyTagged_Str(840)
r1 = 'rollup'
r2 = ' '
r3 = CPyStr_Build(3, r0, r2, r1)
return r3

[case testIntConstantFoldingFinal]
from typing import Final
Expand Down