Sobes.tech
Middle

How to stop a generator on the fly and clear memory? How to close a generator?

sobes.tech AI

Answer from AI

In Python, a generator can be stopped prematurely using the close() method. This method raises a GeneratorExit exception inside the generator, allowing it to perform cleanup (such as releasing resources) before finishing.

Example:

def my_generator():
    try:
        yield 1
        yield 2
    except GeneratorExit:
        print("Generator closed")
        raise

gen = my_generator()
print(next(gen))  # 1

# Stop the generator and clean up memory
gen.close()  # Will output: Generator closed

If the generator does not handle GeneratorExit, it simply terminates. After calling close(), the generator is considered closed, and further calls to next() will raise StopIteration.

Thus, to stop a generator on the fly and free memory, you should call close(). This is especially important if the generator uses external resources (files, connections, etc.).