RuntimePython Error

ValueError

ValueError: generator already executing

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    next(g)
ValueError: generator already executing

What causes this error

Code attempted to advance (next/send/throw) a generator that is currently in the middle of executing. This happens in reentrant scenarios where the generator tries to advance itself.

How to fix it

Restructure code to avoid re-entering the generator. Use a queue to decouple production and consumption. Ensure generators are not shared between threads without synchronization.

Code that causes this error

Broken
def gen():
    yield next(g)  # trying to advance itself

g = gen()
next(g)

Fixed code

Fixed
def gen():
    yield 1
    yield 2

g = gen()
print(next(g))  # 1
print(next(g))  # 2

About ValueError

This ValueError is raised when you try to send a value to or call next() on a generator that is already running. This happens in reentrant scenarios where code inside the generator tries to advance the same generator — for example, a generator that references itself through a callback or a signal handler. Generators are designed for cooperative, sequential execution: you advance them one step at a time, and they yield back control.

Trying to advance a generator from within itself creates an impossible state. This error is rare in normal code but can appear in complex callback-driven architectures, signal handlers, and thread-unsafe generator usage. The fix is to restructure the code to avoid re-entering the generator — use a queue or buffer to decouple the producer and consumer.

Common scenarios

1

Infinite recursion from missing or incorrect base cases

2

Modifying dictionaries or sets during iteration

3

Calling generators or coroutines in unsupported ways

4

Using asyncio event loops incorrectly or attempting to nest them

Related errors