Modern Dependency Injection Container for Python 3.12+
fromtypingimportProtocolfromuncoupled.containerimportContainer, Depends# Define the protocol (i.e the interface)classIService(Protocol):
defcompute(self) ->int: ...
# Define a concrete implementation of the protocolclassServiceImpl(IService):
defcompute(self) ->int:
return42# Inject with `Depends` the required protocoldefmy_function(svc: IService=Depends(IService)) ->None:
print(svc.compute()) # Should return 42 !if__name__=="__main__":
# Create a container and map a protocol to an implementation with a specific lifetimeContainer.create().add_transient(IService, ServiceImpl)
# Call the function without arguments, `Depends` will take care of the injectionmy_function()Have a look at the
examplefolder for more examples !