environment-variablespydantictyping

How to convert a string to a dict variable from an env file in a Pydantic model?


I want to use string representation of dict in my env file. It is look like:

# .env
a="a"
b="b"
c='{"s": 1, ...}'

I am make pydantic BaseSetting model for it and make model for my variable "c" in env:

class C_MODEL(BaseModel):
    s: int
    ...

class Settings(BaseSettings):

    class Config: 
        env_file = '.env'
        env_file_encoding = 'utf-8'

    a: str 
    b: str = "default"
    c: C_MODEL = C_MODEL()

settings: Settings = Settings()

But when I try to make instance I have:

pydantic.error_wrappers.ValidationError: 1 validation errors for C_MODEL

I think BaseModel can't typing string to dict and make validation for class C_MODEL.

How can I make dict from string in env file in this case to make C_MODEL structure and use:

settings: Settings = Settings()
settings.c.s # == 1

in my code?

I read information from pydantic documentation about SettingsBase class and didn't find anything.

I am also read about validator and root_validator, but can't make any work code with it.

P.S: No problem with path to env file, only type of variable from it.


Solution

  • You can either:

    make a dict out of an encoded JSON env var by just describing a field as a dict as described here

    class _Settings(BaseSettings):
        c: dict
    

    or you can directly create a class and use it as a type hint, but don't forget to populate env variable upfront

    example.py

    class YourCustomField(BaseModel):
        foo: str
        baz: int
    
    
    class _Settings(BaseSettings):
        c: YourCustomField
    

    .env

    c={"foo":"bar", "baz": 1}