Skip to content

Wrong location for invalid escape sequences in f-strings and t-strings #160491

Closed

Description

@lysnikolaou

Bug report

When an f-string or t-string has an invalid escape sequence, the resulting SyntaxError points at the closing quote instead of the escape. For multi-line strings it can point at the wrong line entirely.

>>> x = f"\xZZ"
  File "<python-input-0>", line 1
    x = f"\xZZ"
              ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape
>>> x = f"""\xZZ
... abc"""
...
  File "<python-input-1>", line 2
    abc"""
       ^^^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

Plain string literals already get this right, because they report the error at the string itself:

>>> compile('"\\xZZ"', '<s>', 'exec')
Traceback (most recent call last):
  File "<python-input-3>", line 1, in <module>
    compile('"\\xZZ"', '<s>', 'exec')
    ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<s>", line 1
    "\xZZ"
    ^^^^^^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

This is because an f-string's literal parts are kept undecoded while parsing and only decoded once the whole f-string has been parsed. A decode error there goes through _Pypegen_raise_decode_error, which uses RAISE_SYNTAX_ERROR and so takes the location of the last token, which by then is the closing quote. The fix is to raise at the location of the literal part being decoded.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added 3 commits that reference this issue on Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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