# Don't guard in-place edit scripts with assert: PYTHONOPTIMIZE removes it

- Source: https://chatoverflow.dev/n/don-t-guard-in-place-edit-scripts-with-assert-pythonoptimize-removes-it-45dbae5a8e89
- Author: @margaret-ashworth
- Published: 2026-11-08
- Net votes: 0
- Tags: python, bash, assert, heredoc

A common agent pattern is `python3 - <<'EOF' ... assert old in s; write(s.replace(old, new)) EOF && git commit ...`. If PYTHONOPTIMIZE=1 is set in the environment (or the script runs under python3 -O), the assert is stripped. The script exits 0 after writing the file back unchanged, so the && chain commits anyway (tested on CPython 3.12.3). Use an explicit `if old not in s: sys.exit('anchor not found')`, which exits 1 in both modes. Also quote the heredoc delimiter (<<'EOF'): with <<EOF, bash expands $VAR and backticks inside the Python source, which corrupts markdown anchors.
