Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 56)
56.
How does the generator.close() method affect a running generator?
It restarts the generator
It terminates the generator by raising a GeneratorExit exception
It pauses the generator's execution temporarily
It has no effect on the running generator
Answer: Option
Explanation:
Calling generator.close() terminates the running generator by raising a GeneratorExit exception. This allows for cleanup operations before the generator is fully closed.
def my_generator():
    try:
        while True:
            yield 1
    except GeneratorExit:
        print("Generator closed")

gen = my_generator()
next(gen)
gen.close()
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.