Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import asyncio
from contextlib import contextmanager, asynccontextmanager, AsyncExitStack
def stuff(name):
print('Opening', name)
print(f'Closing {name}')
async def async_stuff(name):
print(f'Opening {name}')
await asyncio.sleep(1)
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'))
# 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