[Python] pyyaml resolver: 'type' object is not iterable

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to resolve environment variables in yaml config

    For example, I want to convert

    car:
    name: ${CAR_NAME}
    is_new: true


    to

    car:
    name: BMW
    is_new: true


    My code

    # base_model.py

    import yaml
    import os
    import re

    from pydantic import BaseModel
    from typing import Union
    from pathlib import Path


    env_pattern = re.compile(r".*?\${(.*?)}.*?")
    def env_constructor(loader, node):
    value = loader.construct_scalar(node)
    for group in env_pattern.findall(value):
    value = value.replace(f"${{{group}}}", os.environ.get(group))
    return value

    yaml.add_implicit_resolver("!pathex", env_pattern, yaml.SafeLoader)
    yaml.add_constructor("!pathex", env_constructor, yaml.SafeLoader)


    class YamlModel(BaseModel):
    @classmethod
    def from_yaml(cls, yaml_file_path: Union[str, Path]) -> "YamlModel":
    yaml_file = Path(yaml_file_path)
    with open(yaml_file, "r") as f:
    file_content = yaml.safe_load(f)

    return cls.parse_obj(file_content)


    My test

    import pytest
    import pydantic

    from src.example_model import Config


    def test_config_positive():
    config = Config.from_yaml("tests/config_positive.yaml")
    assert config.owner.name == "John Doe"
    assert config.owner.age == 30
    assert config.car.name == "BMW"


    I have an error:

    tests/test_example_model.py:4: in <module>
    from src.example_model import Config
    src/example_model.py:1: in <module>
    from src.base_model import YamlModel
    src/base_model.py:17: in <module>
    yaml.add_implicit_resolver("!pathex", env_pattern, yaml.SafeLoader)
    venv/lib/python3.11/site-packages/yaml/__init__.py:280: in add_implicit_resolver
    loader.Loader.add_implicit_resolver(tag, regexp, first)
    venv/lib/python3.11/site-packages/yaml/resolver.py:34: in add_implicit_resolver
    for ch in first:
    E TypeError: 'type' object is not iterable



    Full code https://github.com/mascaiTemplates/yaml_config_validator_template

    Continue reading...

Compartilhe esta Página