Skip to content

[python3_13] The parser cannot distinguish whitespace in f-strings #4685

@andrewstein

Description

@andrewstein

In the examples of https://docs.python.org/3.13/reference/lexical_analysis.html#formatted-string-literals there is an example:

>>> foo = "bar"
>>> f"{ foo = }" # preserves whitespace
>>> " foo = 'bar'"

I have confirmed this behavior on the command line with cpython:

Python 3.10.15 | packaged by conda-forge | (main, Oct 16 2024, 01:24:20) [Clang 17.0.6 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = 'bar'
>>> print(f'{     foo     =      }')
     foo     =      'bar'

And the results are similar in python 3.13.9.

However, by the time the f-string f'{ foo = }' hits the parser, it cannot be distinguished from f'{foo=}', f'{foo = }', f'{ foo= }', etc.

Quoting from the spec:

When the equal sign '=' is provided, the output will have the expression text, the '=' and the evaluated value. Spaces after the opening brace '{', within the expression and after the '=' are all retained in the output.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions