Skip to content

Raw f-string format spec undocumented behavior change between 3.11 and 3.12 #137314

@MeGaGiGaGon

Description

@MeGaGiGaGon

Bug report

Bug description:

I found this while working on astral-sh/ruff#19546 .

Between 3.11 and 3.12, the behavior of raw f-string format specifiers changed.

On 3.11 and earlier, the rawness of the f-string is respected in the format specifier:

PS ~>uvx python@3.11 -c @'
class UnchangedFormat:
    def __format__(self, format):
        return format

print("Non-raw output:", repr(f"{UnchangedFormat():\xFF}"))
print("Raw output:", repr(rf"{UnchangedFormat():\xFF}"))
'@
Non-raw output: 'ÿ'
Raw output: '\\xFF'

On 3.12 and later, the rawness of the f-string is not respected:

PS ~>uvx python@3.12 -c @'
class UnchangedFormat:
    def __format__(self, format):
        return format

print("Non-raw output:", repr(f"{UnchangedFormat():\xFF}"))
print("Raw output:", repr(rf"{UnchangedFormat():\xFF}"))
'@
Non-raw output: 'ÿ'
Raw output: 'ÿ'

This new behavior looks to have been carried to t-strings on 3.14 and later:

PS ~>uvx python@3.14 -c @'
class UnchangedFormat:
    def __format__(self, format):
        return format

print("Non-raw output:", repr(t"{UnchangedFormat():\xFF}"))
print("Raw output:", repr(rt"{UnchangedFormat():\xFF}"))
'@
Non-raw output: Template(strings=('', ''), interpolations=(Interpolation(<__main__.UnchangedFormat object at 0x00000183F9904EC0>, 'UnchangedFormat()', None, 'ÿ'),))
Raw output: Template(strings=('', ''), interpolations=(Interpolation(<__main__.UnchangedFormat object at 0x00000183F9908A50>, 'UnchangedFormat()', None, 'ÿ'),))

I could not find any information/documentation about how the rawness of f-strings affect their format specifiers, despite looking in:

CPython versions tested on:

3.12, 3.11, 3.14

Operating systems tested on:

Windows

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)topic-parsertype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions