Skip to content

Instantly share code, notes, and snippets.

@1st1
Created October 22, 2019 21:39
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 1st1/d9860cbf6fe2e5d243e695809aea674c to your computer and use it in GitHub Desktop.
Save 1st1/d9860cbf6fe2e5d243e695809aea674c to your computer and use it in GitHub Desktop.
import time
import threading
def generator():
try:
print('STARTED')
time.sleep(5)
yield 1
finally:
print('FINALIZED')
def close_it():
print('Atttempting to close')
try:
gen.close()
except BaseException as ex:
print(f"Couldn't close {type(ex).__name__}: {ex}")
else:
print('Closed!')
gen = generator()
threading.Timer(1, close_it).start()
gen.send(None)
@1st1
Copy link
Author

1st1 commented Oct 22, 2019

Output:

STARTED
Atttempting to close
Couldn't close ValueError: generator already executing
FINALIZED

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