Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Show how context managers do not support suspended execution
class CM:
mode = 0
def __init__(self, m):
self.m = m
def __enter__(self):
self.old = CM.mode
CM.mode = self.m
def __exit__(self, *_):
CM.mode = self.old
def fizz():
with CM('fizz'):
for _ in range(3):
yield f'fizz({CM.mode})'
def buzz():
with CM('buzz'):
for _ in range(3):
yield f'buzz({CM.mode})'
for f, b in zip(fizz(), buzz()):
print(f, b)
@allemangD
Copy link
Author

allemangD commented Nov 1, 2018

Note how fizz iterations have the wrong mode after the first iteration of buzz.

As in the await code, one would expect the body of each generator to use the same context, but they do not:

fizz(fizz) buzz(buzz)
fizz(buzz) buzz(buzz)
fizz(buzz) buzz(buzz)

The first fizz iteration is the only one with the correct mode - fizz(fizz).


The expected output is:

fizz(fizz) buzz(buzz)
fizz(fizz) buzz(buzz)
fizz(fizz) buzz(buzz)

Where each iteration of both generators occurs in the correct context.

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