Skip to content

Instantly share code, notes, and snippets.

@allemangD
Created November 1, 2018 02:12
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 allemangD/f2534f16d3a0c642c2cdc02c544e854f to your computer and use it in GitHub Desktop.
Save allemangD/f2534f16d3a0c642c2cdc02c544e854f to your computer and use it in GitHub Desktop.
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