pydantic-v2pydantic-settings

Pydantic and Pydantic settings parsing a list


We are trying to use pydantic and pydantic settings in our django app

We have an environment setting such as ENV_VAR = A,B,C,

if I use

env_var: list[str] = []

I get a pydantic parsing error

if I use

env_var: str = []

it parses this but further code treats it as a str

ie

for var in ENV_VAR: print (var)

fails

I tried a custom validator to split the env var but this made no difference

Thanks for any help


Solution

  • Option #1:
    export your environment variable in a format:

    ENV_VAR=[A,B,C]
    

    Option #2:
    export your environment variable in a format:

    ENV_VAR='"A,B,C"'
    

    Pydantic will recognize this value as a complex structure and execute json.loads()

    # CODE WRITTEN IN PYDANTIC V2
    
    class Settings(BaseSettings):
        ENV_VAR: List[str]
    
        @model_validator(mode="before")
        def parse_your_env_var(cls, values: dict) -> dict:
    
            env_var: str = values.get("ENV_VAR", "") # If there is no value for your variable you can raise an error
            values["ENV_VAR"] = [v.strip() for v in env_var.split(",")]
            return values
    

    POV: see the answer