SyntaxWarning
SyntaxWarning: invalid escape sequence
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
pattern = "\d+\.\d+" # \d is not a recognized escape
SyntaxWarning: invalid escape sequenceWhat causes this error
Code contains syntax that is technically valid but likely a mistake. The most common case is unrecognized backslash escape sequences in regular strings.
How to fix it
Use raw strings (r'...') for regex patterns and Windows paths. Use forward slashes or pathlib for file paths. Replace `is` with `==` for value comparisons. Fix assertion tuples to proper assert statements.
Code that causes this error
pattern = "\d+\.\d+" # \d is not a recognized escape
Fixed code
pattern = r"\d+\.\d+" # raw string, no escape issues
About SyntaxWarning
A SyntaxWarning is issued for dubious syntax that is not technically invalid but is likely a bug. The most common SyntaxWarning in modern Python is 'invalid escape sequence', which occurs when a string contains a backslash followed by a character that is not a recognized escape sequence (like `\p` or `\s`). In Python 3.12+, invalid escape sequences will become SyntaxError (previously they were just warnings).
This most commonly affects Windows file paths (`'C:\Users\name'`) and regular expression patterns (`'\d+\.\d+'`) where developers forget to use raw strings. Other SyntaxWarnings include 'is' with a literal (use == instead), and assertion tuples that are always true. Addressing SyntaxWarnings is important because they often become full errors in future Python versions.
Common scenarios
Using deprecated APIs that will be removed in future versions
Performing numerical operations that produce inf or NaN values
Leaving files, sockets, or connections open without proper cleanup
Calling async functions without awaiting the result