CodeBlanks Logo Icon CodeBlanks

close

Learn to close with generator.close().

The close method

The g.close() call terminates the generator. At the awaited yield point, the generator receives the GeneratorExit exception; it can catch it with try/except to do cleanup.

Example: try:\n yield 1\nexcept GeneratorExit:\n print("closed"). The call g.close() raises GeneratorExit and the except block runs. This is used to release a resource when the generator ends; it is useful for files, network connections and similar resources.

Ideal for cleanup

close() is ideal for cleanup when the generator ends. Closing opened files, freeing network sockets or flushing buffers can be done by catching GeneratorExit.

However, after GeneratorExit is caught, you should not call yield; otherwise a RuntimeError is raised. Doing cleanup and not re-raising the exception is also fine; the generator ends silently.

Practice Close the generator with close

Define the function def gen():. In the body open a try: block; inside write yield 1 and yield 2. Open an except GeneratorExit: block; inside write print("closed"). Create an instance with g = gen(), print the first value with print(next(g)) and close the generator with g.close().

Starter code

main.py
# Close the generator with close

Sample solution

main.py
# Close the generator with close
def gen():
    try:
        yield 1
        yield 2
    except GeneratorExit:
        print("closed")

g = gen()
print(next(g))
g.close()

Expected output

1
closed

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does close() raise?

  • GeneratorExit Correct answer
  • StopIteration
  • ValueError
  • TypeError

Explanation: close() raises GeneratorExit into the generator.

2 close call

Question
g = gen()
print(next(g))
g.____()
Answer
g = gen()
print(next(g))
g.close()

Explanation: close() terminates the generator.

3 Match the close parts

Term Meaning
close() Termination
GeneratorExit Exception
try/except Catch
cleanup Cleanup

All lessons in Intermediate