Skip to content

Unexpected whitespace handling in f-string !r #93283

@dimaqq

Description

@dimaqq

Bug report

The handling of whitespace around the argument in literal string interpolation (f-string) is unexpected when a conversion specifier (e.g. !r) is applied.

Consider

f"{None}"  # OK
f"{ None }"  # OK
f"{None!r}"  # OK
f"{ None!r }"  # SyntaxError

# details
f"{ None!r}  # OK
f"{None !r}  # OK
f"{None!r }  # SyntaxError

PEP-498 states:

Leading and trailing whitespace in expressions is ignored
For ease of readability, leading and trailing whitespace in expressions is ignored. This is a by-product of enclosing the expression in parentheses before evaluation.

I suppose that the text above may be technically accurate, but is misleading to common folk:
In the example above, None is enclosed in parentheses (None) but not None!r.

There are no mentions of whitespace in the rest of the PEP.

Formal reproducer:

> python3.11 -c 'print(f"{ None!r }")'
  File "<string>", line 1
    print(f"{ None!r }")
                       ^
SyntaxError: f-string: expecting '}'

Your environment

  • CPython versions tested on: 3.8, 3.9, 3.10, 3.11a2, 3.11a7
  • Operating system and architecture: Linux, MacOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.10only security fixes3.11only security fixes3.12only security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy