Product case study · November 25, 2026

Claude Code: Fix Python Validation That Vanishes Under -O

Reproduce a Python assert check disappearing under -O, ask Claude Code for a bounded repair, and verify rejected inputs in both interpreter modes.

Reading time
6 min
Checked
Nov 25, 2026
Paper validation gates on parallel tracks separate blue circular tokens from ochre triangles beside blank evidence cards
A required input check must survive a change in how Python starts.
Bottom line

Use explicit exceptions for required input validation, then run the same acceptance checks with and without Python optimization.

Your Python helper rejects an unsupported delivery method on your laptop. The same file accepts it when started with python3 -O. The input did not change: the validation disappeared.

This lab gives Claude Code a narrow repair: preserve the accepted methods and reject everything else in both interpreter modes. You will finish with a two-command check you can rerun independently of the agent.

Sources checked November 25, 2026. The synthetic Python reproduction, reference repair and verifier were run locally. The Claude Code prompt is an authored exercise; we did not run an authenticated Claude session or measure agent success rates.

Why the check disappears

Python’s assert statement reference describes assertions as debugging checks. Its code generator omits them when optimization is requested. A required input boundary should therefore use an explicit conditional and exception.

The interpreter options reference documents -O, along with -OO, which also discards docstrings. The PYTHONOPTIMIZE environment variable can enable optimization too. A difference between local and deployed launch settings is enough to expose this bug.

This does not mean every assertion needs replacing. An internal debugging assumption and a promise to reject unsupported user input serve different purposes. Here, rejection is part of the function’s public contract.

1. Create the failing example

Use Python 3 and Bash in a new scratch folder. Claude Code should already be installed and authenticated if you want to follow the agent step; the first-session lesson covers that setup. No Python packages or network calls are needed for the fixture.

mkdir delivery-validation-lab
cd delivery-validation-lab
python3 --version
cat > delivery.py <<'PY'
def delivery_label(method):
    assert method in ("email", "download"), "unsupported delivery method"
    return "delivery:" + method
PY
python3 -E -c 'from delivery import delivery_label; print(delivery_label("fax"))'
python3 -E -O -c 'from delivery import delivery_label; print(delivery_label("fax"))'

Run the commands separately if your shell stops on the first error. The first Python call should fail with AssertionError. The optimized call prints delivery:fax and exits successfully. That output demonstrates the defect; no message is actually sent.

We use -E to ignore Python environment variables for these controlled runs, including a pre-existing PYTHONOPTIMIZE setting. It is not an operating-system sandbox. The second command explicitly adds -O, making the difference visible in the command itself.

The contract for the repair is small:

InputRequired result
"email"Return "delivery:email"
"download"Return "delivery:download"
Any other valueRaise ValueError("unsupported delivery method")

Do not normalize case, trim whitespace or introduce another delivery method. Those would be separate product decisions.

2. Freeze a check that also survives optimization

Save this as verify.py beside delivery.py. It deliberately uses explicit branches instead of bare assertions: a verifier whose checks vanish would give false confidence.

from delivery import delivery_label

cases = 0
for method in ("email", "download"):
    actual = delivery_label(method)
    expected = "delivery:" + method
    if actual != expected:
        raise SystemExit(f"FAIL: {method!r}: {actual!r} != {expected!r}")
    cases += 1

for method in ("fax", "", "EMAIL", " email", None, 0, []):
    try:
        actual = delivery_label(method)
    except ValueError as exc:
        if str(exc) != "unsupported delivery method":
            raise SystemExit(f"FAIL: wrong error message for {method!r}")
    except Exception as exc:
        raise SystemExit(
            f"FAIL: {method!r} raised {type(exc).__name__}, expected ValueError"
        )
    else:
        raise SystemExit(f"FAIL: accepted {method!r} as {actual!r}")
    cases += 1

print(f"PASS: {cases} delivery cases")

Run both commands before editing:

python3 -E verify.py
python3 -E -O verify.py

Both should fail on the original function. The normal run reports the wrong exception type; the optimized run reports that it accepted "fax". This distinguishes two requirements: a stable error contract and rejection that remains active.

3. Ask Claude Code for the bounded repair

Start claude in this scratch folder, check the displayed workspace, and give it the following prompt. Anthropic’s best-practices guide recommends supplying a concrete check the agent can run. The contract and test cases here are our exercise, not a vendor-provided test.

Read delivery.py and verify.py in this practice folder.
Reproduce the failure with both:
  python3 -E verify.py
  python3 -E -O verify.py

Change only delivery.py. Keep verify.py unchanged.
Only the exact strings email and download are supported.
Return delivery: followed by the supported method.
For every other fixture value, raise ValueError with the exact message
unsupported delivery method in normal and optimized Python.

Explain why the existing validation differs between interpreter modes.
Make the smallest repair, without dependencies or changes to launch flags.
Run both checks again. Report the commands, exit codes and actual output.
Do not send messages, access external services or edit outside this folder.

Review proposed tool actions under your existing permissions. The prompt defines scope; it does not itself enforce filesystem isolation. If the agent proposes removing -O, changing the expected inputs or rewriting the verifier, steer it back to repairing delivery.py.

4. Compare the patch with the reference

A sufficient repair is:

def delivery_label(method):
    if method not in ("email", "download"):
        raise ValueError("unsupported delivery method")
    return "delivery:" + method

The explicit branch remains part of normal execution. The tuple membership check also lets the supplied list fixture reach the intended rejection; replacing the tuple with a set would raise TypeError for that unhashable input before reaching our exception.

This is a small local helper, not a general validator for arbitrary Python objects with custom comparison behavior. For an API boundary, define the accepted serialized input types and validate that contract separately.

Run the two verification commands yourself after the edit. Each should print PASS: 9 delivery cases and exit with code 0. In our local check, the original failed in both modes and the reference repair passed all nine cases in both modes. Those are fixture results, not evidence that an AI agent repaired a production application.

Read verify.py again to confirm it still checks the original contract. Save the Python version, before/after source and command output with your exercise notes. If you use Git for the practice folder, inspect the diff before accepting the change.

Recover when the evidence disagrees

ObservationWhat to check next
The first reproduction unexpectedly accepts "fax"Confirm the file still contains the original assertion and the command includes -E without -O.
Normal mode passes but optimized mode failsLook for remaining required checks inside assert or if __debug__ branches.
Both modes print success immediatelyConfirm the verifier contains the rejection cases and explicit failure branches shown above.
The list fixture raises TypeErrorCheck whether membership was changed to a set without first defining and checking input types.
Claude reports success without command outputRun both commands yourself; a summary is not the acceptance evidence.

For a real codebase, start with one externally reachable input check and the project’s existing tests. Record how the actual service starts, then add a regression case for the relevant launch mode. Avoid a repository-wide assertion replacement: each use needs a decision about whether it expresses a debugging assumption or required behavior.

Official sources

Checked November 25, 2026:

Put this to work

Distinguish a debugging assertion from a required validation branch.

Try

Repair a synthetic delivery-method validator with Claude Code in a scratch folder.

Prove it worked

Reject unsupported methods and preserve valid outputs with and without -O.

Keep in view

  • Python can omit assert statements when optimization is enabled.
  • Give the agent a failure it can reproduce in a second interpreter mode.
  • Keep the verification script free of bare assert statements too.
Learn the workflow: Set up your first Claude Code project session