Pydantic with dotenv support does not set environment variables. It is not clear to me if this is intentional, but dotenv support suggests variables from .env file should be also available in os.environ.
Consider following .env file and test script:
.env:
TEST_PREFIX_VARIABLE=42
test.py
#!/usr/bin/env python
from dotenv import load_dotenv
from os import environ
from pydantic import BaseSettings
class TestSettings(BaseSettings):
variable: str
class Config:
env_file = '.env'
env_prefix = 'TEST_PREFIX_'
if __name__ == "__main__":
print('before:', environ.get('TEST_PREFIX_VARIABLE'))
settings = TestSettings()
print('after pydantic:', environ.get('TEST_PREFIX_VARIABLE'))
load_dotenv()
print('after dotenv:', environ.get('TEST_PREFIX_VARIABLE'))
Result:
before: None
after pydantic: None
after dotenv: 42
Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":
pydantic version: 1.5.1
pydantic compiled: False
install path: [cut]/lib/python3.6/site-packages/pydantic
python version: 3.6.10 (default, Feb 5 2020, 11:02:42) [GCC 9.2.0]
platform: Linux-5.5.7-arch1-1-x86_64-with-arch
optional deps. installed: ['typing-extensions']
Ok, it seems I misunderstood how this works 🤦♂️ I should call load_dotenv() anyway and then create settings object without specifying env_file.
Yes, the dotenv support only supports reading from the .env file, at which point you can get anything that's set in the Settings instance. Extra things wouldn't be read in to the environment.
I'm getting the same issue, shouldn't this be able to work without having to manually call load_dotenv()?
I just can't get it to work when specifying a Field(..., env="ENV_KEY") for the life of me, either. Just invariantly says field required (type=value_error.missing)... Or at least it doesn't respect my prefix. So many weird combinations necessary to make this work ^^