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

Type casting in dependency_injector.providers.Configuration.from_env

Open gtors opened this issue 3 years ago • 3 comments

It would be useful to be able to cast env variables to a specific type, for example:

def setup_config(config: Configuration):
    config.foo.from_env("VAR_FOO", cast=int, default=1)
    config.bar.from_env("VAR_BAR", cast=bool, default=True)

Inspired by https://www.starlette.io/config/ and https://github.com/sloria/environs

gtors avatar Dec 06 '21 23:12 gtors

Not a bad idea. At the moment it's done in the different place:

    api_client_factory = providers.Factory(
        ApiClient,
        api_key=config.api.key,
        timeout=config.api.timeout.as_int(),  # <--- type case here
        # timeout=config.api.timeout.as_(Decimal),  # <--- or like this
    )

It should be more convenient to specify it once while calling .from_env().

Thanks @gtors , will add it to the backlog.

rmk135 avatar Dec 07 '21 11:12 rmk135

Hm, maybe we name it as_, not cast? Considering speed Python adds new features, I wonder if cast becomes a system keyword one day :) Also, it aligns better with current API (as_*() methods).

def setup_config(config: Configuration):
    config.foo.from_env("VAR_FOO", as_=int, default=1)
    config.bar.from_env("VAR_BAR", as_=bool, default=True)

What do you think @gtors ?

rmk135 avatar Dec 07 '21 12:12 rmk135

Looks acceptable 👍🏻

gtors avatar Dec 07 '21 14:12 gtors