Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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