# Fix "SyntaxWarning: invalid escape sequence" on Python 3.12

Yes. An agent fixes each invalid escape by the method that keeps the string's value identical, and proves it by comparing the parsed code before and after.

[Run this on Rush](https://cloud.getrush.ai/run/fix-invalid-escape-sequence-syntax-warning/python/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

Python 3.12 started printing `SyntaxWarning: invalid escape sequence '\d'` for string literals that contain a backslash followed by a character with no escape meaning. The usual advice is to add an `r` prefix. That is right most of the time and changes the string the rest of the time, so the agent begins with an inventory. In mchaput/whoosh, compiling every `.py` file on 3.12 reports eight literals in five files, of four different kinds. Two are regular expressions: `re.compile("^\w+", re.UNICODE)` at line 33 of `src/whoosh/lang/paicehusk.py` and `RegexTokenizer("\w+")` at line 523 of `tests/test_analysis.py`. One is a replacement template, `ccy_exp.sub('\g<1>Y', word)` in `lang/porter2.py`. Three are docstrings whose examples contain `\S`, in `analysis/filters.py` and `analysis/intraword.py`. One is a multi-line verbose pattern at line 50 of `filters.py`, and one is a default argument listing delimiter characters at line 285 of `intraword.py`.

For each literal it evaluates the string twice, as written and with a raw prefix, and compares. Five of the eight come out identical, so a prefix is safe there. Three do not. The verbose URL pattern is the instructive one: its first lines spell the escapes correctly as `\\S` and `\\s`, and a later line has a bare `\w`. Make that literal raw and the correctly doubled backslashes turn into two characters each, which changes what the pattern matches. The delimiter string mixes `\"`, a real escape for a quote, with `\|`, an invalid one; raw would add a backslash in front of the quote. The third is a docstring that also contains `\\`. For those three the fix is to double only the offending backslash and touch nothing else in the literal.

The proof does not depend on the test suite. An invalid escape keeps its backslash, so a correct fix leaves every string byte for byte the same, and that can be checked for the whole file: parse it before and after with warnings silenced and compare the two syntax trees. On whoosh the edit is a few single-line changes in each of the five files, the trees are equal for every one of them, a fresh compile reports no warnings, and `python -W error -c "import whoosh.analysis"`, which fails before the change with `SyntaxError: invalid escape sequence '\w'`, imports cleanly. That last command matters to anyone whose CI turns warnings into errors: for them this is not a warning, the package cannot be imported.

The agent also explains why the warning seemed to come and go. Python 3.11 reports the same strings as a `DeprecationWarning`, which is hidden by default, so importing the package there prints nothing. On 3.12 the first import of a fresh checkout prints five warnings and the second prints none, because the compiled bytecode is cached and the check only runs when a file is compiled. Developers see it once after a pull; a container build or a clean CI runner sees it every time. Finally it reports what it found and left alone: one file under `stress/` still uses Python 2 `print` statements and cannot be compiled at all, which is a separate matter from escapes.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Python 3.12 prints \"SyntaxWarning: invalid escape sequence\" for this project. Compile every Python file in the repository with warnings recorded, without relying on cached bytecode, and list each affected string literal with its file, line and the kind of string it is: a regular expression, a replacement template, a docstring, a path or something else. Report separately any file that does not compile at all, and leave it alone. For each affected literal, evaluate it as written and as a raw string and compare the two values. Where they are equal, add the r prefix; for a docstring, make it a raw docstring. Where they differ, because the literal also contains valid escapes such as a doubled backslash, an escaped quote or a newline escape, do not use a raw string: double only the invalid backslash. Do not touch byte strings or f-strings differently from this rule, and do not reformat anything else. Then prove no string changed: for every edited file, parse the old and the new source and confirm the two syntax trees are identical. Recompile everything and confirm there are no warnings, and import the package's main modules with python -W error. If a literal looks like a real bug, for example a backslash-b in a pattern that was meant as a word boundary but is a backspace character, do not change its value; list it. Open a pull request with the inventory table, the result of the tree comparison and the list of anything suspicious.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request whose diff is a few characters per line: an added prefix here, a doubled backslash there. For whoosh it stays inside the five files of the inventory. The description holds the inventory, each literal with its kind and whether a raw prefix was safe, and the statement that the syntax tree of every edited file is unchanged. It also shows the import under `-W error` failing before and succeeding after.

A reviewer does not need to reason about each regular expression. The tree comparison says no string has a different value, so the review is to confirm the comparison was run on every edited file and to read the short list of literals the agent flagged but did not change. Those are the ones where the existing value may itself be wrong, and deciding that is a human call with a test attached, not part of silencing a warning.

## Run it on every warning in a clean CI build

Because cached bytecode hides the warning on developer machines, the place it shows reliably is a clean build. If your CI logs go to a log platform that can call an HTTP endpoint with a custom header when a pattern matches, point that alert at a Rush `webhook` trigger and send `Authorization: Bearer` with the trigger's secret. If it can only send its own signed webhook, receive it on a handler you run and forward the matching log lines to the trigger from there.

The forwarded body is added after the saved prompt as event text, at most 64 KB of it. One fix clears every build, so set the automation's max runs per hour to one or two; an event past that waits `queued` until the hour has room, and repeats of the same alert can simply be dropped by your handler.

## Why run it on Rush?

Whether you see this warning depends on the state of a cache, which makes a laptop a poor place to confirm it is gone. The sandbox starts from a fresh clone with no compiled files, so the first compile reports everything, and the agent can install 3.11, 3.12 and a newer interpreter side by side to show how each one treats the same source. Every command and its output is kept with the session, including the tree comparison that is the actual proof.

It also turns a job that invites a careless global replace into one with a guarantee. Adding `r` to every flagged string with an editor macro is fast and, in this repository, would have altered three strings out of eight without any test necessarily noticing. The run classifies each literal first, applies the edit that preserves it, and hands back evidence that nothing a user can observe has changed.

## Frequently asked questions

### Is adding an r prefix always the right fix?

No. It is right when the literal contains no escapes that Python was already interpreting. If the same string has `\\`, `\"` or `\n` that were meant as escapes, a raw prefix changes their meaning. In those cases double only the invalid backslash, for example `\\w`.

### Why does the warning appear only sometimes?

It is raised when Python compiles a source file, not when it runs it. After the first import the bytecode is cached, so later runs are silent until the file changes or the cache is cleared. Clean CI runners and container builds compile everything each time and always show it.

### Will this become an error?

Python's documentation says invalid escape sequences will eventually raise `SyntaxError`. It already is an error for anyone running with `-W error`: on whoosh, importing the analysis package that way fails at the first affected literal.

### How can I be sure no regular expression changed?

An invalid escape sequence keeps its backslash, so a correct fix produces exactly the same string. The agent parses each edited file before and after and compares the syntax trees, which contain every string's value. Equal trees mean equal strings.

## More Python jobs

- [Fix "ValueError: invalid mode: 'rU'" on Python 3.11 and Later](https://getrush.ai/run/fix-invalid-mode-ru-value-error/python/)
- [Fix "ModuleNotFoundError: No module named 'cgi'" on Python 3.13](https://getrush.ai/run/fix-no-module-named-cgi/python/)
- [Fix "ModuleNotFoundError: No module named 'imp'" on Python 3.12](https://getrush.ai/run/fix-no-module-named-imp/python/)

## More jobs like this: Fix a bug from an alert

- [Fix ValueError: Invalid hash method 'sha256' After a Werkzeug Upgrade](https://getrush.ai/run/fix-invalid-hash-method-sha256/werkzeug/)
- [Fix "java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter" on Java 11 and Later](https://getrush.ai/run/fix-javax-xml-bind-noclassdeffounderror/jaxb/)
- [Fix "Test environment jest-environment-jsdom cannot be found" After Upgrading to Jest 28 or 29](https://getrush.ai/run/fix-jest-environment-jsdom-not-found/jest/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
