Skip to content
Sarj Code Standards

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

Before — flagged A service method hides cleanup in an exit stack with pop_all
app/uploader.py
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()
After — preferred The application lifespan owns resource closing
app/lifespan.py
from collections.abc import AsyncIterator
from contextlib import AsyncExitStack, asynccontextmanager
@asynccontextmanager
async def lifespan(app) -> AsyncIterator[None]:
async with AsyncExitStack() as resources:
app.state.client = await resources.enter_async_context(open_client())
yield