# Fix "RuntimeError: generator raised StopIteration" in Python 3.7 and Later

Yes. An agent finds the generator that raises StopIteration to finish early, works out which inputs reach it, replaces it with return, and adds the missing test.

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

## What the agent does

Since Python 3.7, a `StopIteration` that escapes from inside a generator is converted into `RuntimeError: generator raised StopIteration`. Old code used `raise StopIteration` as a way to end a generator early, and it kept working for years, so the line is usually in a branch that rarely runs. The agent's task is to find the line and then the inputs that reach it. mozilla/DSAlign has one. In `align/utils.py`, the generator `enweight` pairs each item of a list with a positional weight. When the list has fewer than two items it yields the single item, if there is one, and then line 123 says `raise StopIteration`. Any list of two or more items takes the other path and never touches that line.

The agent follows the callers to turn that into concrete inputs. `align/text.py` wraps it: `weighted_ngrams` returns `enweight(ngrams(s, size))`, and `similarity` calls that for every N-gram size from 1 to 3 by default. A string no longer than the N-gram size produces at most one N-gram, so a string of three characters or fewer reaches the bad line. The agent runs it and records the results: `similarity('hello world', 'hello word')` returns a number, and `similarity('ab', 'ab')` raises the error in the title. The second caller is `align/align.py`, which weights the fragments of a recording, so a recording that yields a single fragment takes the same path. One short phrase in a transcript is enough to stop a long alignment job.

The fix is one word: `return` in place of `raise StopIteration`. The agent then checks the small cases: an empty list gives an empty result, a single item gives one pair with weight 1, and `similarity('ab', 'ab')` comes out as 1.0. The neighbouring file already shows the correct idiom. `ngrams` in `text.py` ends its early branch with a plain `return`, which the agent cites so the change reads as consistency and not as a new opinion.

It then searches for the other form of the same mistake, which no text search for `raise StopIteration` finds: a bare `next(iterator)` inside a generator, where an exhausted iterator raises the exception for you. It reports each generator it inspected. Last, it deals with the interpreter question honestly. The repository's `requirements.txt` pins `deepspeech==0.7.1`, which publishes wheels for CPython 3.5 to 3.8, so the full pipeline cannot be installed on a current Python. The agent tests the pure-Python functions on 3.7 and on a current interpreter, where they behave the same, and says plainly that the end-to-end tool was not run.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "This project fails with \"RuntimeError: generator raised StopIteration\". Find every generator function that can let a StopIteration escape: an explicit raise StopIteration, and any next() call without a default inside a generator body, including generator expressions and functions that yield. For each one, trace the callers and work out which real inputs reach the failing line; give a minimal call that reproduces the error and run it, saving the traceback. Replace raise StopIteration with return, and guard each bare next() with a default or a try block that returns. Do not change what the generator yields for inputs that already worked. For each fixed generator, state its result for the edge cases (empty input, a single item) and check that against its docstring or its callers' expectations. Add tests for those edge cases; if the project has no test suite, add a small one that runs with the standard library or pytest and say how to run it. Run the reproduction and the tests on the oldest Python version the project's dependencies can be installed on and on a current Python, and report exactly which parts of the project you could run and which you could not because of pinned dependencies. Open a pull request with the reproduction before and after, the list of generators you inspected, and anything else you noticed but did not change.",
  "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 code change is a single line in `align/utils.py`, with a new test file beside it. The repository has no tests today, so the description explains how to run the new ones and what they cover: the empty list, the single item, and strings of one, two and three characters through `similarity`. It shows the traceback from the minimal call before the change and the returned values after it.

A reviewer checks two things beyond the diff. One is the list of generators the agent inspected, because the claim is that no other one can leak the exception, and the list is how that claim can be audited. The other is the boundary of the evidence. The description separates the functions that were executed from the alignment pipeline that was only read, and names the pinned dependency that kept the full tool from being installed on a current interpreter.

## Run it on every batch job that crashes on one input

This error arrives hours into a batch run, on the one input that takes the rare branch. Have the job report its own failure: wrap the command in a script that, when the process exits with a traceback containing `generator raised StopIteration`, posts the traceback and the name of the input it was processing to the URL of a `webhook` trigger on an automation that holds the prompt above. The script sends `Authorization: Bearer` with the trigger's secret. The posted body, up to 64 KB, is placed after the saved prompt as event text, which gives the agent a real failing input to start from.

A batch that restarts will hit the same input again. Send an `Idempotency-Key` header to the trigger's URL made from the traceback's last frame, and keep the automation's max runs per hour low.

## Why run it on Rush?

The line is trivial to change and hard to trust. What a reviewer needs is the set of inputs that reach it and proof that the generator behaves for them afterwards. The agent produces both by running the code in its own sandbox, on an old interpreter and a new one, and the session keeps each command and its output. The pull request quotes results; it does not ask to be believed.

It also stops at the edge of what it could execute. Research code with pinned, ageing dependencies often cannot be installed whole, and a fix that pretends otherwise is worse than none. A run that reports which functions it ran and which it only read gives the maintainers an accurate basis for merging.

## Frequently asked questions

### Why does raise StopIteration cause a RuntimeError?

PEP 479 changed generators so that a `StopIteration` raised inside one is no longer treated as normal completion. From Python 3.7 it is replaced with `RuntimeError`, because a stray one from a nested `next()` call used to end loops silently and hide bugs.

### What should I write instead?

A bare `return`. Inside a generator, `return` ends iteration cleanly, and the caller's `for` loop or `list()` simply stops. If you need to pass a final value to a `yield from` caller, use `return value`.

### My code has no raise StopIteration. Where does the error come from?

Usually from `next(it)` inside a generator when `it` is exhausted. Give `next` a default, as in `next(it, None)`, or catch `StopIteration` around it and `return`. The agent checks every generator for this form, since searching for the `raise` text will not find it.

### Why did this code work for years?

Older interpreters accepted it, and the branch that raises is often an edge case such as an empty or one-item input. The code can run on common input indefinitely and fail the first time a short one arrives.

## More Python jobs

- [Fix "SyntaxWarning: invalid escape sequence" on Python 3.12](https://getrush.ai/run/fix-invalid-escape-sequence-syntax-warning/python/)
- [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/)

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

- [Fix `Call to undefined function get_magic_quotes_gpc()` When a PHP App Lands on PHP 8](https://getrush.ai/run/fix-get-magic-quotes-gpc-removed/php/)
- [Fix "TypeError: glob is not a function" after upgrading the glob package](https://getrush.ai/run/fix-glob-is-not-a-function/glob/)
- [Fix "Global built-in functions are deprecated and will be removed in Dart Sass 3.0.0" warnings](https://getrush.ai/run/fix-global-built-in-functions-are-deprecated-warning/sass/)

## 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/)
