python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Do I should use the Configuration provider?

Open NiKuma0 opened this issue 2 years ago • 1 comments
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)

NiKuma0 avatar Aug 23 '23 13:08 NiKuma0

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()

vlad-ghita avatar Dec 14 '24 16:12 vlad-ghita