Skip to content
Sarj Code Standards

no-injected-dependency-close

Leave closing an injected dependency to the owner that constructed it.

Why

The code that constructs a resource owns its lifetime. When a consumer closes a client it received through __init__, other consumers sharing that client fail after the first one closes, the owner may close it twice, and shutdown order is no longer decided in one place.

Fix

Register the resource's cleanup where it is created: for an application, in the composition root or the lifespan exit stack. Remove the consumer's close of what it was given. Objects the class constructs itself may still be closed by the class.

Examples

Before — flagged A consumer closes the client it was given
speech/synthesizer.py
from contextlib import AsyncExitStack
from openai import AsyncOpenAI
class Synthesizer:
def __init__(self, *, client: AsyncOpenAI) -> None:
self._client = client
async def aclose(self) -> None:
async with AsyncExitStack() as cleanup:
cleanup.push_async_callback(self._client.close)
After — preferred The owner that constructs the client registers its cleanup
speech/synthesizer.py
from contextlib import AsyncExitStack
from openai import AsyncOpenAI
class Synthesizer:
def __init__(self, *, client: AsyncOpenAI) -> None:
self._client = client
async def serve(stack: AsyncExitStack) -> Synthesizer:
client = await stack.enter_async_context(AsyncOpenAI())
return Synthesizer(client=client)