exit-stack-requires-lifecycle-owner
Own exit stacks only where resource lifetime is handed to the caller or the process root.
Why
An ExitStack inside ordinary application code hides resource ownership in a dynamic callback list: readers must replay registrations, conditional entries and pop_all() transfers to learn what is closed and when. Clients and cleanups are easier to reason about when the composition root (lifespan, entry point or context manager) opens them once and closes them in one place.
Fix
Inject already-open clients and let the lifespan, main or an @asynccontextmanager own closing. For a fixed set of resources use one multi-item async with. To transfer ownership, return a context manager to the caller instead of guarding with pop_all(); for rollback on failure use try/except that performs the compensating action and re-raises.
Examples
from contextlib import AsyncExitStack
class Uploader: def __init__(self, client): self._client = client
async def upload(self, items): async with AsyncExitStack() as cleanup: cleanup.push_async_callback(self._client.discard, items) await self._client.publish(items) cleanup.pop_all()from collections.abc import AsyncIteratorfrom contextlib import AsyncExitStack, asynccontextmanager
@asynccontextmanagerasync def lifespan(app) -> AsyncIterator[None]: async with AsyncExitStack() as resources: app.state.client = await resources.enter_async_context(open_client()) yield