⬅︎ Back to GeneratorExit - How to clean up after the last yield in Python
This got me thinking (after playing recently with try/finally, inspired by golang's defer), would try/finally work here? It seems it does```def tf(): try: for i in range(10): try: yield i finally: print("Sent", i) finally: print("Done")for i in tf(): print("Got", i) if i == 3: breakresults inGot 0Sent 0Got 1Sent 1Got 2Sent 2Got 3Sent 3Done
Actually, I kinda like your solution better. However, today was the first time I've ever needed or used GeneratorExit and I guess it gives you slightly more control.
Comment
This got me thinking (after playing recently with try/finally, inspired by golang's defer), would try/finally work here? It seems it does
```
def tf():
try:
for i in range(10):
try:
yield i
finally:
print("Sent", i)
finally:
print("Done")
for i in tf():
print("Got", i)
if i == 3:
break
results in
Got 0
Sent 0
Got 1
Sent 1
Got 2
Sent 2
Got 3
Sent 3
Done
Replies
Actually, I kinda like your solution better.
However, today was the first time I've ever needed or used GeneratorExit and I guess it gives you slightly more control.