Support generator functions and yield from

Merged
RE
8d ago
+3853-307

Re-implementation of pydantic/monty#1020 on top of main.

  • Generator functions, yield, yield from and send(), including lambdas and methods
  • StopIteration(value) and .value, with generator return values keeping their identity
  • PEP 479: a StopIteration escaping a generator or coroutine becomes RuntimeError, caused by the original
  • Generators advance through py_next, so for, next(), list()/sum()/sorted() and the itertools adaptors consume them
  • Host calls suspend inside generator bodies and yield from delegates, and snapshots carry running and paused generators
  • CPython's SyntaxErrors for yield outside a function or inside a comprehension, and for yield from inside async def
  • Dump version 18, with the released dump_v17.bin kept as an older fixture
  • docs/limitations/generators.md

šŸ¤– Generated with Claude Code


Summary by cubic

Implements generator functions and expressions, yield, yield from, and send(), which previously raised NotImplementedError. Generators run as pushed frames: yield returns to the caller and return raises StopIteration(value), so for and next() drive them as usual. Generator expressions now produce lazy generator objects instead of materializing to lists.

  • Eager native consumers (list, sum, sorted, itertools adaptors, str/bytes.join, list/deque.extend, set/dict/Counter.update) drain a generator argument in a suspendable for loop, so a generator body that calls the host works under them; any()/all() stop at the deciding item. The drain hook resolves the receiver method through the type's table, so hashlib.sha256().update(gen) and os.path.join(gen) no longer consume the argument. * unpacking cannot suspend, so asyncio.gather(*(f(x) for x in xs)) with a host f raises NotImplementedError.
  • send and __next__ are attribute-table methods on the generator type, so unbound generator.send(g, x) resolves and checks its receiver like CPython.
  • StopIteration(value) keeps .value by reference, and an escaping StopIteration becomes RuntimeError (PEP 479) caused by the original.
  • The parser rejects yield outside a function, inside a comprehension, and yield from inside async def, with CPython's SyntaxError messages.
  • Dumps carry running and paused generators — including a host call suspended inside a generator or yield from delegate — and resume them; the dump format moves to version 18.
  • Documents limitations: throw()/close(), generator introspection attributes, and async generators.