Closed
Description
Problem: if model has both extra="allow"
and env_prefix
set, then model will have all envvars regardless of prefix, essentially ignorring env_prefix
config.
Expected behavior: fields that match env_prefix
can be added into model, even if they are not declared.
Noticed that it changed when upgraded, remember that in 2.1 it was clsoer to that, but also actually didn't include undeclared vars from .env . But having undeclared vars in .env that is shared between multiple nested settings files broke my code :)
Example code:
from pydantic_settings import BaseSettings
class MySettings(BaseSettings):
class Config:
env_prefix = "MY_PREFIX_"
case_sensitive = False
env_file = ".env"
extra = "allow"
not_in_a_file: str = "yes"
inside_file: bool = False
obj = MySettings()
print(obj)
if not obj.inside_file:
print(".env/MY_PREFIX_inside_file is not detected, even though it's declared.")
if "notaprefix" in obj.model_dump():
print("undeclared var that doesn't match prefix got into object.")
if not "bar" in obj.model_dump():
print("did not get undeclared but matching prefix envvar: .env/MY_PREFIX_BAR")
if "my_prefix_bar" in obj.model_dump():
print("\t... but it is there with it's prefix.")
respective .env
to test:
NOTAPREFIX=True
MY_PREFIX_inside_file=True
MY_PREFIX_BAR=1
So latest main gives this output:
not_in_a_file='yes' inside_file=True notaprefix='True' my_prefix_bar='1'
undeclared var that doesn't match prefix got into object.
did not get undeclared but matching prefix envvar: .env/MY_PREFIX_BAR
... but it is there with it's prefix.
and v2.1.0
gives this:
not_in_a_file='yes' inside_file=True
did not get undeclared but matching prefix envvar: .env/MY_PREFIX_BAR