ets-labs/python-dependency-injector

Bug: Configuration.from_yaml() cannot read properly template strings in a yaml file

Closed this issue · 5 comments

Hi, I'm using Configuration.from_yaml() to read template strings in a yaml file like below:

template_string:  |-
  Hi! My name is ${name}.
  I'm ${age} years old.
  I'm living in ${country}.

And When I read the yaml file, the variables string in the yaml file disappear.

class Container(DeclarativeContainer):
    config = Configuration()
    config.from_yaml(yaml_dir / "introduce.yaml")
    ...

container = Container()
print(container.config.template_string())
# Hi! My name is .\nI'm years old.\nI'm living in .

But when I use pyyaml directly, it doesn't have any problem.

class Container(DeclarativeContainer):
    config = Configuration()
    config.from_pydantic(PydanticConfig())

    # config.from_yaml(yaml_dir / "introduce.yaml")
    introduce_yaml_path = yaml_dir / "introduce.yaml"
    with open(introduce_yaml_path, "r") as f:
        loaded = yaml.safe_load(f)
        config.from_dict(loaded)

print(container.config.template_string())
# Hi! My name is ${name}.\nI'm ${age} years old.\nI'm living in ${country}.

Could you guys clear up what happens in from_yaml()?
Thanks!

Funnily enough, this once was a feature #467. I think it is possible to make this behavior optional.

Apparently, this is because _resolve_config_env_markers() in from_yaml() considers variable placeholders(${...}) in yaml file as environment variable placeholders and tries to replace them with environment variable or None.

How about add a parameter like enable_env_markers=True to from_yaml() so that we make calling _resolve_config_env_markers optional?

I've repurposed existing arg to receive envs_required=None. PR with this change (#861) is already merged, will be available in the next release.

That's cool! Thanks for your consideration :)

Fixed in v4.46.0 (#861).