Skip to content

t-strings: AST unparsing does not reproduce original formatting #133581

Closed
@JelleZijlstra

Description

@JelleZijlstra

Bug report

Bug description:

The AST unparsing of Interpolation objects does not reproduce formatting within interpolations.

This is true both for ast.unparse in Python:

>>> ast.unparse(ast.parse('t"{a   + b}"'))
"t'{a + b}'"

And for the C unparse that is used by from __future__ import annotations:

>>> ns = {}
>>> exec("""
... from __future__ import annotations
... def f(x: t"{a    + b}"): ...
... """, ns)
>>> ns["f"].__annotations__
{'x': "t'{a + b}'"}

In general, we can't recover the original source exactly, but in this case we do have the original source available:

>>> ast.parse('t"{a   + b}"').body[0].value.values[0].str
'a   + b'

Let's use it.

CPython versions tested on:

3.14

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.14bugs and security fixesstdlibPython modules in the Lib dirtopic-parsertype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions