Use context managers with dependencies
masterIf you bind a class or a function to a context manager (using bind_to_provider or bind), python-inject will use the object as-is. If the object is a context manager, it will be managed by the caller's lifecycle (e.g., when used in an @inject.autoparams function), ensuring resources like connections or files are properly destroyed.
import contextlib
import inject
@contextlib.contextmanager
def get_file_sync():
obj = MockFile()
yield obj
obj.destroy()
def config(binder):
# Binding a provider that returns a context manager
binder.bind_to_provider(MockFile, get_file_sync)
inject.configure(config)
@inject.autoparams()
def example(file: MockFile):
# 'file' will be automatically destroyed when 'example' exits
pass