Skip to content

Apply the !r, !s and !a conversions in f-strings - #937

Merged
craigbarratt merged 1 commit into
custom-components:masterfrom
jfriend00:fstring-conversions
Dec 2, 2026
Merged

craigbarratt merged 1 commit into
custom-components:masterfrom
jfriend00:fstring-conversions

Conversation

@jfriend00

Copy link
Copy Markdown
Contributor

Apply the !r, !s and !a conversions in f-strings

What was broken

In an f-string, pyscript ignored the conversion after !: {x!r} and {x!a} gave str(x), with no error. Python's = specifier ({x=}) also uses repr() when there's no format spec, so it lost the quotes too:

x = "soon"
log.warning(f"demo: {x!r} {x=} {'°F'!a}")
# Python:   demo: 'soon' x='soon' '\xb0F'
# pyscript: demo: soon x=soon °F

In log messages, those quotes are what show an empty string, a trailing space, or None versus "None".

Why

ast_formattedvalue() evaluated the value and the format spec, but never looked at the node's conversion field.

What I changed

ast_formattedvalue() applies the conversion (repr(), str() or ascii()) before the format spec, as Python does.

Testing

Six new cases in tests/test_unit_eval.py, after the existing f-string case, each checked against CPython: each conversion, a conversion with a format spec (including a nested one, {x!r:{w}}), and = alone, with !s and with a format spec. Without the change, five of them fail; the {n=:.2f} case passes either way, since = with a format spec doesn't use repr(). tests/test_unit_eval.py passes (34 tests), and ruff, codespell, pylint and mypy are clean. This ran on Windows with local stand-ins for Home Assistant's Linux-only imports, so CI is its first Linux run.

@craigbarratt craigbarratt left a comment

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.

Thanks @jfriend00, looks good. Matches CPython on every case I tried, including nested specs, {d=:%Y} and !a. Approving.

@craigbarratt
craigbarratt merged commit 8492ecb into custom-components:master Dec 2, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants