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

Configuration object is a dictionary and not an object with which the dot notation could be used to access its elements

Open Zevrap-81 opened this issue 1 year ago • 1 comments

I cannot figure out why the config is a dictionary, while in every example it is an object with "." (dot) operator to access its variables.

Here is a simple code that I used:

from dependency_injector import containers, providers
from dependency_injector.wiring import Provide, inject


class Container(containers.DeclarativeContainer):
    config = providers.Configuration()


@inject
def use_config(config: providers.Configuration = Provide[Container.config]):
    print(type(config))
    print(config)



if __name__ == "__main__":
    container = Container()
    container.config.from_yaml("config.yaml")
    container.wire(modules=[__name__])

    use_config()

and the type is a 'dict'

Zevrap-81 avatar Sep 02 '24 12:09 Zevrap-81

I'm experiencing the same problem.

daewon avatar Sep 13 '24 02:09 daewon

Yes, the injected config is supposed to be a dict type. Dot notation can be used in the Declarative container and in the Provide notation, but not after the config has been injected, it will return the type of object at the key specified or a dict if the whole config is injected.

For example, if you need to inject a certain key, from the config, that can be done like this:

# ...
@inject
def use_config(config: providers.Configuration = Provide[Container.config.key]):
    print(type(config))
    print(config)
#...

Aesonus avatar Jan 04 '25 16:01 Aesonus

Yes, the injected config is supposed to be a dict type.

It's supposed to? Why? (Especially when defining settings via Pydantic Settings)

marcammann avatar Jun 04 '25 21:06 marcammann

@Zevrap-81

I cannot figure out why the config is a dictionary, while in every example it is an object with "." (dot) operator to access its variables.

Configuration stores its internal state as a dict. When you access it like Container.config.key, you'll get an another Provider configured to look up for a key in that internal dict.

@marcammann

Especially when defining settings via Pydantic Settings

container.from_pydantic(settings) is roughly equivalent to container.from_dict(settings.model_dump()) (assuming pydantic v2+).

ZipFile avatar Jun 06 '25 07:06 ZipFile