The doc of generator.close() says as shown below:
Raises a GeneratorExit at the point where the generator function was paused.
But generator.close() never raises GeneratorExit as shown below:
def func(): yield 'Hello' yield 'World' v = func() print(v.close()) # None print(v.close()) # None
def func(): yield 'Hello' yield 'World' v = func() print(next(v)) # Hello print(v.close()) # None print(v.close()) # None
def func(): yield 'Hello' yield 'World' v = func() print(next(v)) # Hello print(next(v)) # World print(v.close()) # None print(v.close()) # None
def func(): yield 'Hello' yield 'World' v = func() print(v.close()) # None print(next(v)) # StopIteration
def func(): yield 'Hello' yield 'World' v = func() print(next(v)) # Hello print(v.close()) # None print(next(v)) # StopIteration
3.13
Windows
generator.close() sends the GeneratorExit to the yield inside the generator, not to caller of close. For example:
def a(): try: yield "123" except GeneratorExit: print("gotcha!") gen = a() next(gen) gen.close() # gotcha!
Do you have any suggestions to make the documentation clearer?
I think it's also helpful to emphasize this sentence later in the paragraph:
If the generator function is already closed, or raises GeneratorExit (by not catching the exception), close() returns None.
gh-135110: Fix misleading `generator.close()` documentation (GH-135152)
pythongh-135110: Fix misleading `generator.close()` documentation (py…
[3.13] gh-135110: Fix misleading `generator.close()` documentation (G…
[3.14] gh-135110: Fix misleading `generator.close()` documentation (G…
Activity
ZeroIntensity commented on Jun 4, 2025
generator.close() sends the GeneratorExit to the yield inside the generator, not to caller of close. For example:
Do you have any suggestions to make the documentation clearer?
ryan-duve commented on Jun 4, 2025
I think it's also helpful to emphasize this sentence later in the paragraph:
gh-135110: Fix misleading `generator.close()` documentation (GH-135152)
pythongh-135110: Fix misleading `generator.close()` documentation (py…
pythongh-135110: Fix misleading `generator.close()` documentation (py…
[3.13] gh-135110: Fix misleading `generator.close()` documentation (G…
[3.14] gh-135110: Fix misleading `generator.close()` documentation (G…
pythongh-135110: Fix misleading `generator.close()` documentation (py…
pythongh-135110: Fix misleading `generator.close()` documentation (py…
pythongh-135110: Fix misleading `generator.close()` documentation (py…
pythongh-135110: Fix misleading `generator.close()` documentation (py…