Checks
Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())"
:
pydantic version: 1.9.0
pydantic compiled: True
install path: /private/tmp/settings/.venv/lib/python3.10/site-packages/pydantic
python version: 3.10.1 (main, Jan 6 2022, 17:54:04) [Clang 13.0.0 (clang-1300.0.29.30)]
platform: macOS-11.6.4-arm64-arm-64bit
optional deps. installed: ['dotenv', 'typing-extensions']
Bug
When nesting a model in a Settings
class and populating it with an environment file, pydantic does not match environment variables to variables of nested models if the latter is upper cased. Example (adapted from the tutorial).
I'm thinking this is a bug because capitalization of non-nested models is handled correctly. However, if it's somehow expected behaviour, perhaps a mention in the documentation could help people out who tend to use upper case variable names for settings.
Assume the following .env
file:
export V0=0
export V1=0
export SUB_MODEL__V2=information
Then the following code runs fine:
from pydantic import BaseModel, BaseSettings
class SubModel(BaseModel):
v2: str # <-- lower case
class Settings(BaseSettings):
v0: str
V1: str
sub_model: SubModel
class Config:
env_nested_delimiter = "__"
s = Settings(_env_file='.env')
print(s.dict())
"""
{'v0': '0', 'V1': '0', 'sub_model': {'v2': 'information'}}
"""
but the following crashes (the only change is the capitalization of SubModel.V2
):
from pydantic import BaseModel, BaseSettings
class SubModel(BaseModel):
V2: str # <-- upper case
class Settings(BaseSettings):
v0: str
V1: str
sub_model: SubModel
class Config:
env_nested_delimiter = "__"
s = Settings(_env_file='.env')
print(s.dict())
"""
Traceback (most recent call last):
File "/private/tmp/settings/pyds.py", line 15, in <module>
s = Settings(_env_file='.env')
File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.__init__
File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for Settings
sub_model -> V2
field required (type=value_error.missing)
"""
I'm guessing that pydantic/pydantic#3115 is affected by the same bug (if it is a bug), but since capitalization isn't mentioned I thought it would be best to create a new issue.
PS: Thanks for a great library π₯