Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot load prefixed nested model from dotenv. #279

Closed
voodoo11 opened this issue Apr 23, 2024 · 3 comments
Closed

Cannot load prefixed nested model from dotenv. #279

voodoo11 opened this issue Apr 23, 2024 · 3 comments
Assignees

Comments

@voodoo11
Copy link

How to reproduce:

Given .env:

NESTED_FOO=foo
BAR=bar
from pydantic_settings import BaseSettings, SettingsConfigDict


class NestedConfig(BaseSettings):
    foo: str = ""
    model_config = SettingsConfigDict(env_prefix="NESTED_")


class Config(BaseSettings):
    nested: NestedConfig = NestedConfig()
    bar: str = ""
    model_config = SettingsConfigDict(
        env_file=".env", env_file_encoding="utf-8", extra="ignore", case_sensitive=False
    )


print(Config())

results in:

nested=NestedConfig(foo='') bar='bar'

Setting env variable by hand e.g. NESTED_FOO=foo python test.py works fine.

@hramezani
Copy link
Member

Couple of points:

Here is the working example:

from pydantic import BaseModel
from pydantic_settings import BaseSettings, SettingsConfigDict


class NestedConfig(BaseModel):
    foo: str = ""


class Config(BaseSettings):
    nested: NestedConfig = NestedConfig()
    bar: str = ""
    model_config = SettingsConfigDict(
        env_file=".env", env_file_encoding="utf-8", extra="ignore", case_sensitive=False, env_nested_delimiter="__"
    )


print(Config())

@voodoo11
Copy link
Author

voodoo11 commented Apr 23, 2024

@hramezani Thanks, that makes sense. Is it possible then to override model config for submodels somehow?

@hramezani
Copy link
Member

pydantic-settigns only loads the config for the models you are initializing(Config in your example) and collect values for the model fields. so it only consider the parent model configs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants