Skip to content

Instantly share code, notes, and snippets.

@reinderien
Created May 7, 2022
Embed
What would you like to do?
Generators close context managers
class SomeCtx:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('I exited')
def some_generator():
with SomeCtx():
for i in range(10):
yield i
for i in some_generator():
print(f'Consumed {i}')
if i >= 7:
raise ValueError()
print('The loop must have succeeded')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment