Skip to content

RUF027 creates invalid f-string interpolations with backslashes before Python 3.12 #21033

@dscorbett

Description

@dscorbett

Summary

missing-f-string-syntax (RUF027) applies to putative interpolations containing backslashes, which are not valid until Python 3.12. The fix can therefore introduce syntax errors. RUF027 should probably be suppressed for such strings before Python 3.12. Example:

$ cat >ruf027.py <<'# EOF'
x = "!"
print("{'\''}{x\
}")
# EOF

$ python3.11 ruf027.py
{'''}{x}

$ ruff --isolated check ruf027.py --select RUF027 --preview --target-version py311 --unsafe-fixes --fix --output-format concise
ruf027.py:2:11: invalid-syntax: Cannot use an escape sequence (backslash) in f-strings on Python 3.11 (syntax was added in Python 3.12)
ruf027.py:2:17: invalid-syntax: Cannot use an escape sequence (backslash) in f-strings on Python 3.11 (syntax was added in Python 3.12)
Found 3 errors (1 fixed, 2 remaining).

$ python3.11 ruf027.py 2>&1 | tail -n 1
SyntaxError: f-string expression part cannot include a backslash

Version

ruff 0.14.1 (2bffef5 2025-10-16)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixesRelated to suggested fixes for violations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions