Created
November 1, 2018 02:12
-
-
Save allemangD/f2534f16d3a0c642c2cdc02c544e854f to your computer and use it in GitHub Desktop.
Show how context managers do not support suspended execution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note how
fizz
iterations have the wrong mode after the first iteration ofbuzz
.As in the
await
code, one would expect the body of each generator to use the same context, but they do not:The first
fizz
iteration is the only one with the correct mode -fizz(fizz)
.The expected output is:
Where each iteration of both generators occurs in the correct context.