Skip to content

Instantly share code, notes, and snippets.

@messa
Created January 8, 2019 15:51
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 messa/caa470c69fdc4df08ed0dc578eaf8105 to your computer and use it in GitHub Desktop.
Save messa/caa470c69fdc4df08ed0dc578eaf8105 to your computer and use it in GitHub Desktop.
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