Skip to content

Commit 994f4ec

Browse files
authored
dotenv no error w/ an env key shorter than prefix (#106) (#107)
1 parent 373af71 commit 994f4ec

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

pydantic_settings/sources.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,7 @@ def __call__(self) -> dict[str, Any]:
578578
# As `extra` config is allowed in dotenv settings source, We have to
579579
# update data with extra env variabels from dotenv file.
580580
for env_name, env_value in self.env_vars.items():
581-
if env_value is not None:
581+
if env_name.startswith(self.env_prefix) and env_value is not None:
582582
env_name_without_prefix = env_name[self.env_prefix_len :]
583583
first_key, *_ = env_name_without_prefix.split(self.env_nested_delimiter)
584584

tests/test_settings.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,37 @@ class Settings(BaseSettings):
680680
assert s.c == 'best string'
681681

682682

683+
prefix_test_env_file = """\
684+
# this is a comment
685+
prefix_A=good string
686+
# another one, followed by whitespace
687+
688+
prefix_b='better string'
689+
prefix_c="best string"
690+
f="random value"
691+
"""
692+
693+
694+
@pytest.mark.skipif(not dotenv, reason='python-dotenv not installed')
695+
def test_env_file_with_env_prefix(env, tmp_path):
696+
p = tmp_path / '.env'
697+
p.write_text(prefix_test_env_file)
698+
699+
class Settings(BaseSettings):
700+
a: str
701+
b: str
702+
c: str
703+
704+
model_config = ConfigDict(env_file=p, env_prefix='prefix_')
705+
706+
env.set('prefix_A', 'overridden var')
707+
708+
s = Settings()
709+
assert s.a == 'overridden var'
710+
assert s.b == 'better string'
711+
assert s.c == 'best string'
712+
713+
683714
@pytest.mark.skipif(not dotenv, reason='python-dotenv not installed')
684715
def test_env_file_config_case_sensitive(tmp_path):
685716
p = tmp_path / '.env'

0 commit comments

Comments
 (0)