pydantic / pydantic-settings

Settings management using pydantic
https://docs.pydantic.dev/latest/usage/pydantic_settings/
MIT License
502 stars 47 forks source link

.env file takes precedence over os env with Field setting #325

Closed palunel closed 1 week ago

palunel commented 1 week ago

I have the following

from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict

from devtools import debug

class Config(BaseSettings):

    # Environment
    STAGE: str = Field('prod', validation_alias='STAGE')
    OTHER: str

    model_config = SettingsConfigDict(env_file='.test.env', env_file_encoding='utf-8', env_prefix='DEV_')

settings = Config()

debug(settings)

with a .test.env file that looks like this:

STAGE=test
DEV_OTHER="other"

and I set an OS environment variable as follows:

export STAGE=dev

giving the following response with printenv:

...
STAGE=dev
...

and then get the following output:

test.py:18 <module>
    settings: Config(
        STAGE='test',
        OTHER='other',
    ) 

My understanding is that the OS environment variable will take precedence but I am not seeing it here?

palunel commented 1 week ago

The issue is not Pytdantic-related, but the visibility of environment variables and the respective processes in which they are created. A variable created via export in a shell is only available to that shell and any subprocess spawned from that shell. It needs to be persisted through adding to ~/.zshrc or similar before being available to other processes.