python-dependency-injector
python-dependency-injector copied to clipboard
Do I should use the Configuration provider?
trafficstars
This code works pretty well:
class Settings(BaseSettings):
...
class Container(containers.DeclarativeContainer):
config = providers.Singleton(Settings)
...
I used pydantic settings, but I think this example can be used for any other settings library.
But providers.Confinguration has the from_pydantic method (and many other integration methods), for what? Should I use it instead of the Singleton provider?
I just want to know the best practice and would appreciate any explanation)
Here's my conclusion.
# Purposefully didn't use `pydantic.Settings` b/c with `provider.Configuration` we can inject configuration before instantiating the config.
#
# Achieving this with Pydantic is not possible.
#
# class Settings(pydantic.Settings):
# foo: str
#
# class Foo:
# def __init__(self, foo: str) -> None:
# self.foo = foo
#
# class Container(containers.DeclarativeContainer)
# settings = providers.Dependency(instance_of=pydantic.Settings)
# foo1 = providers.Factory(Foo, foo=settings.foo) # throws error: settings provider doesn't have foo attribute
# foo2 = providers.Factory(Foo, foo=settings().foo) # throws error: settings dependency is not yet fulfilled
self._config = providers.Configuration()