Product case study · November 20, 2026

Ask Claude Code why a valid Python batch comes back empty

A validation pass can consume every record in a Python generator. Reproduce the bug, give Claude Code a fixed contract, and verify the repair locally.

Reading time
6 min
Checked
Nov 20, 2026
Blue paper cards travel through a charcoal inspection arch into a collection tray, beside a preserved stack on warm paper.
Checking a stream uses it. Keep the accepted records as you go.
Bottom line

For a small finite batch, collect and validate in one pass. Test a generator explicitly: a list can hide the bug.

The batch passed validation. Every name was present and nonblank. Then the function returned an empty list, because checking the records had already used them up.

This is a lovely small debugging exercise for Claude Code: the obvious test passes, and the useful test changes only how the input arrives. Give the function a list and it works. Give it a generator over the same names and the result disappears.

You’ll need Bash on macOS, Linux or WSL, Python 3, and an installed, signed-in Claude Code. The Python fixture and reference repair below were tested locally. The Claude prompt is an authored exercise, not a recorded agent run. Official sources were checked November 20, 2026.

Reproduce the disappearing batch

Create a practice folder with this deliberately broken function:

batch_lab=$(mktemp -d /tmp/claude-batch.XXXXXX)
cd "$batch_lab"
cat > batch.py <<'PY'
def collect_names(names):
    if not all(name.strip() for name in names):
        raise ValueError("blank name")
    return list(names)


if __name__ == "__main__":
    values = ["brief", "guide", "report"]
    print("list:", collect_names(values))
    print("generator:", collect_names(name for name in values))
PY
python3 batch.py

The baseline prints:

list: ['brief', 'guide', 'report']
generator: []

The function traverses its input twice: once inside all(), then again inside list(). A list supports another traversal. A generator is an iterator whose position advances as values are consumed. Python’s iterator reference specifies that an exhausted iterator stays exhausted; starting another loop does not rewind it.

The built-in function reference explains the other half: all() reads until it encounters a false value or reaches the end. Here every name passes, so validation consumes the whole generator. For invalid input it can stop earlier. Either way, it has read part of the stream.

I would keep this reproduction tiny. Adding a CSV reader or an API response would make the bug look more realistic while making its cause harder to see.

Tell the agent what a batch means

Save this as SPEC.md:

collect_names(names) accepts a finite iterable of strings.
Return a list containing every supplied string in its original order.
Preserve duplicates and original whitespace; do not normalize names.
Reject empty or whitespace-only strings with ValueError.
An empty iterable returns an empty list.
Support lists and one-shot generators.
Do not mutate an input list or return that same list object.
The result must fit in memory. Infinite inputs are outside this contract.
Only batch.py may change. Keep SPEC.md and test_batch.py fixed.
Use the Python standard library only. No file writes or network calls.

The whitespace rule is deliberate. Checking name.strip() tells you whether a name is blank; returning name.strip() changes the name. A repair should not quietly turn validation into data cleanup.

Save the following as test_batch.py. These six tests define the output independently of the implementation:

import unittest
from batch import collect_names


class BatchTests(unittest.TestCase):
    def test_list_preserves_values_without_aliasing(self):
        source = [" guide ", "brief", "brief"]
        result = collect_names(source)
        self.assertIsInstance(result, list)
        self.assertEqual(result, [" guide ", "brief", "brief"])
        self.assertIsNot(result, source)
        self.assertEqual(source, [" guide ", "brief", "brief"])

    def test_generator_preserves_values(self):
        source = (name for name in [" guide ", "brief", "brief"])
        result = collect_names(source)
        self.assertIsInstance(result, list)
        self.assertEqual(result, [" guide ", "brief", "brief"])

    def test_empty_list(self):
        self.assertEqual(collect_names([]), [])

    def test_empty_generator(self):
        self.assertEqual(collect_names(name for name in []), [])

    def test_blank_list_item(self):
        with self.assertRaises(ValueError):
            collect_names(["brief", "", "report"])

    def test_whitespace_generator_item(self):
        with self.assertRaises(ValueError):
            collect_names(name for name in ["brief", " \t", "report"])

Run them before asking for a patch:

python3 -m unittest -v test_batch

Locally, six tests ran and one failed: the nonempty generator returned []. The list and invalid-input tests passed. That is exactly why a list-only test suite would miss this bug. Python’s unittest documentation describes this module invocation and the assertions used here.

Give Claude the failing case, not the answer

Start claude in the practice folder and paste:

Read SPEC.md, batch.py and test_batch.py.
Run python3 -m unittest -v test_batch and report the actual baseline.
Explain why the list and generator in the demo produce different results.
Change only batch.py to satisfy the contract. Preserve the demo.
Do not edit tests or SPEC.md, install packages, commit or delegate.
Run the same six tests and the demo after the repair.
Explain whether your function consumes its input and when it returns a result.
Do not claim that this prompt creates a filesystem sandbox.

Anthropic’s debugging workflow recommends providing the reproduction command and error details. Here the failed assertion supplies both. Review Claude’s active permissions and proposed commands; a narrow editing instruction is scope, not enforced isolation.

If Claude suggests iter(names) before each loop, ask it to rerun the generator test. An iterator’s __iter__() returns that iterator itself. It does not make a fresh copy of the source.

Review the loop that keeps what it checks

This reference repair passed the six tests locally:

def collect_names(names):
    accepted = []
    for name in names:
        if not name.strip():
            raise ValueError("blank name")
        accepted.append(name)
    return accepted

It reads each supplied value once, validates it, and keeps the original string. The caller gets the completed list only after the loop finishes. For this contract, I prefer the explicit loop: you can see validation and collection together without mentally tracking two traversals.

Materializing names into a list before validation is also a reasonable repair for small finite inputs. It eagerly reads the entire source, whereas this loop stops at the first blank name. Our contract does not require either consumption pattern on rejection. Neither approach is suitable for an unbounded stream.

After exiting Claude, run the checks yourself:

python3 -m unittest -v test_batch
python3 batch.py

The repaired demo should print the same three names on both lines. If only five tests run, compare the test file with the six methods above. If Python cannot import batch, confirm that both files are in the current practice folder. If the generator result is still empty, check whether validation and collection still read the original input separately.

There is one useful limit to keep in mind: the input generator is consumed, even after a successful repair. Calling the function again on that same generator returns an empty list. To repeat the job, create a new source or retain the returned list. A generator that was already exhausted before the call has no records left for this function to recover.

On rejection, no partial list is returned, but any effects inside the input generator have already happened and are not undone. Keep this lab’s inputs as plain strings; a generator that sends messages or writes files as it yields needs a separate design.

When an agent repairs a function that accepts an iterable, add at least one test that supplies a generator. The values can be identical. The difference is whether they are still there on the second pass.

Sources

Checked November 20, 2026:

Put this to work

Why validating an iterator can consume the data a later loop expects to read.

Try

Repair one Python batch function in a disposable folder using Claude Code.

Prove it worked

Run the same six tests against the broken function and the repair.

Keep in view

  • Reproduce a function that accepts a list but loses a generator's records.
  • Give Claude Code a bounded repair with six fixed acceptance tests.
  • Check that validation preserves order, duplicates and whitespace.
Learn the workflow: Set up your first Claude Code project session