Last active
November 1, 2018 15:40
-
-
Save allemangD/bba8dc2d059310623f752ebf65bb6cdc to your computer and use it in GitHub Desktop.
Show how Context Managers do not correctly 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
import asyncio | |
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 | |
async def long_op(): | |
with CM('long'): | |
print(f'- - mode {CM.mode}') | |
await asyncio.sleep(3) | |
print(f'- - mode {CM.mode} done') | |
async def short_op(): | |
with CM('short'): | |
for i in range(5): | |
print(f'{i} - mode {CM.mode}') | |
await asyncio.sleep(1) | |
print(f'{i} - mode {CM.mode} done') | |
async def main(): | |
await asyncio.gather(short_op(), | |
long_op()) | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is how your example can be fixed with the
contextvars
module: