Resource provider¶
A Resource resolves once, caches the instance, and runs teardown logic from a generator or context manager.
A plain Singleton has no teardown step.
The creator can be a generator or async generator function, with teardown after the yield in finally,
or a class that implements typing.ContextManager or typing.AsyncContextManager.
A Resource does not automatically integrate with container_context.
Use Resource for dependencies that need a single creation step, a single finalization step, and thread and async safety.
All consumers receive the same resource object, and concurrency is handled.
How it works¶
Defining a sync or async resource¶
You can define your creation logic as either a generator or a context manager class (sync or async).
A synchronous generator:
import typing
def create_sync_resource() -> typing.Iterator[str]:
print("Creating sync resource")
try:
yield "sync resource"
finally:
print("Tearing down sync resource")
An asynchronous generator:
import typing
async def create_async_resource() -> typing.AsyncIterator[str]:
print("Creating async resource")
try:
yield "async resource"
finally:
print("Tearing down async resource")
You then attach them to a container:
from that_depends import BaseContainer
from that_depends.providers import Resource
class MyContainer(BaseContainer):
sync_resource = Resource(create_sync_resource)
async_resource = Resource(create_async_resource)
Resolving and teardown¶
Once defined, you can explicitly resolve the resource and tear it down:
# Synchronous resource usage
value_sync = MyContainer.sync_resource.resolve_sync()
print(value_sync) # "sync resource"
MyContainer.sync_resource.tear_down_sync()
# Asynchronous resource usage
import asyncio
async def main():
value_async = await MyContainer.async_resource.resolve()
print(value_async) # "async resource"
await MyContainer.async_resource.tear_down()
asyncio.run(main())
resolve_sync()orresolve()creates the resource instance if needed and returns it.tear_down_sync()ortear_down()cleans up the resource (running yourfinallyblock or exiting the context manager) and resets the cached instance toNone. The next resolve call recreates it.
Concurrency safety¶
Resource is safe to use under threading and asyncio concurrency. Internally, a lock ensures only one resource instance is created per container:
- Multiple threads calling
resolve_sync()simultaneously will produce a single instance for that container. - Multiple coroutines calling
resolve()simultaneously will likewise produce only one instance for that container in an async environment.
# Even if multiple coroutines call resolve in parallel,
# only one instance is created at a time:
await MyContainer.async_resource.resolve()
# Similarly, multiple threads calling resolve_sync concurrently
# still yield just one instance until teardown:
MyContainer.sync_resource.resolve_sync()
Using context managers directly¶
If your resource is a standard context manager or async context manager class, Resource will handle entering and exiting it under the hood. For example:
import typing
from that_depends.providers import Resource
class SyncFileManager:
def __enter__(self) -> str:
print("Opening file")
return "/path/to/file"
def __exit__(self, exc_type, exc_val, exc_tb):
print("Closing file")
sync_file_resource = Resource(SyncFileManager)
# usage
file_path = sync_file_resource.resolve_sync()
print(file_path)
sync_file_resource.tear_down_sync()