RustPython/RustPython · warning · SyntaxWarning
"\{next}" is an invalid escape sequence. Such sequences will
Error message
"\{next}" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\{next}"? A raw string is also an option. What it means
SyntaxWarning raised while RustPython turns a string literal into an AST Constant when the source contains a backslash sequence Python does not recognize (such as \d or \s). Unknown escapes are currently kept literally, but the construct is scheduled to become a SyntaxError, so the compiler warns. The message names the two valid spellings: double the backslash, or use a raw string.
Source
Thrown at crates/vm/src/stdlib/_ast/string.rs:268
}
'N' => {
if let Some('{') = chars.peek().copied() {
chars.next();
for c in chars.by_ref() {
if c == '}' {
break;
}
}
}
true
}
_ => false,
};
if !valid {
let message = vm.ctx.new_str(format!(
"\"\\{next}\" is an invalid escape sequence. Such sequences will not work in the future. Did you mean \"\\\\{next}\"? A raw string is also an option."
));
let _ = warn::warn(
message.into(),
Some(vm.ctx.exceptions.syntax_warning.to_owned()),
1,
None,
vm,
);
}
}
}
fn ruff_format_spec_to_joined_str(
vm: &VirtualMachine,
source_file: &SourceFile,
flags: ast::AnyStringFlags,
format_spec: Option<Box<ast::InterpolatedStringFormatSpec>>,
) -> Option<Box<JoinedStr>> {
match format_spec {
None => None,View on GitHub (pinned to 5dc83d997e)
Solutions
- Use a raw string: r"\d+" instead of "\d+"
- Double the backslash when a raw string is not possible: "\\d"
- Fix the typo if a valid escape was intended (for example \t vs \n confusion)
- Run ruff/flake8 rule W605 or python -W error::SyntaxWarning to surface every occurrence
Example fix
# before pattern = "\d+" # after pattern = r"\d+"
Defensive patterns
Strategy: validation
Validate before calling
import warnings
def compiles_clean(source: str) -> bool:
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", SyntaxWarning)
compile(source, "<check>", "exec")
return not caught Prevention
- Write regex patterns as raw strings by convention (always r-prefix)
- Run ruff or flake8 rule W605 in CI to flag invalid escapes statically
- Compile with -W error::SyntaxWarning during migration to enumerate all sites
When it happens
Trigger: Compiling or parsing source (compile(), ast.parse(), exec, import) that contains non-raw strings with unrecognized escapes: "\d+", "\server\path", "\w+\s+". Most common in regular expressions and Windows file paths; in this code path it surfaces via the _ast string parser when literals become Constant nodes.
Common situations: Regex patterns written without the r-prefix; Windows paths in normal strings; escapes copied from other languages (\s from sed/grep habits); code that worked silently on older interpreters.
AI-assisted analysis of RustPython/RustPython@5dc83d997e (2026-08-17).
Data as JSON: /api/errors/c557e7b500599262.
Report an issue: GitHub.