Skip to content

Instantly share code, notes, and snippets.

@laixintao
Created April 8, 2022 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laixintao/6c7e697ee293b4bf7ba82e0eb0f8ac3e to your computer and use it in GitHub Desktop.
Save laixintao/6c7e697ee293b4bf7ba82e0eb0f8ac3e to your computer and use it in GitHub Desktop.
You can move put try-catch outside of the generator!
import time
def generate():
try:
for i in range(5):
time.sleep(0.5)
yield i
finally:
print("My jos is done, clock out!")
gen = generate()
for x in gen:
print(x)
import time
def generate():
for i in range(5):
time.sleep(0.5)
yield i
try:
gen = generate()
finally:
print("My jos is done, clock out!")
for x in gen:
print(x)
@laixintao
Copy link
Author

laixintao commented Apr 8, 2022

They are different!

stdout:

➜ python in_generator.py 
0
1
2
3
4
My jos is done, clock out!
➜ python out_generator.py 
My jos is done, clock out!
0
1
2
3
4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment