Created
January 8, 2019 15:51
-
-
Save messa/caa470c69fdc4df08ed0dc578eaf8105 to your computer and use it in GitHub Desktop.
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 | |
from contextlib import contextmanager, asynccontextmanager, AsyncExitStack | |
@contextmanager | |
def stuff(name): | |
print('Opening', name) | |
yield | |
print(f'Closing {name}') | |
@asynccontextmanager | |
async def async_stuff(name): | |
print(f'Opening {name}') | |
await asyncio.sleep(1) | |
yield | |
print(f'Closing {name}') | |
async def f(): | |
async with AsyncExitStack() as stack: | |
stack.enter_context(stuff('file 1')) | |
await stack.enter_async_context(async_stuff('connection 1')) | |
stack.enter_context(stuff('file 2')) | |
await stack.enter_async_context(async_stuff('connection 2')) | |
print('Hi!') | |
asyncio.run(f()) | |
# Output: | |
# | |
# Opening file 1 | |
# Opening connection 1 | |
# Opening file 2 | |
# Opening connection 2 | |
# Hi! | |
# Closing connection 2 | |
# Closing file 2 | |
# Closing connection 1 | |
# Closing file 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment