Skip to content

Commit

Permalink
Improve explode_env_vars for better dict handling (#261)
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani committed Mar 27, 2024
1 parent e129a81 commit a853a13
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
12 changes: 9 additions & 3 deletions pydantic_settings/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,8 @@ def explode_env_vars(self, field_name: str, field: FieldInfo, env_vars: Mapping[
Returns:
A dictionary contains extracted values from nested env values.
"""
is_dict = lenient_issubclass(get_origin(field.annotation), dict)

prefixes = [
f'{env_name}{self.env_nested_delimiter}' for _, env_name, _ in self._extract_field_info(field, field_name)
]
Expand All @@ -624,11 +626,15 @@ def explode_env_vars(self, field_name: str, field: FieldInfo, env_vars: Mapping[
target_field = self.next_field(target_field, last_key)

# check if env_val maps to a complex field and if so, parse the env_val
if target_field and env_val:
is_complex, allow_json_failure = self._field_is_complex(target_field)
if (target_field or is_dict) and env_val:
if target_field:
is_complex, allow_json_failure = self._field_is_complex(target_field)
else:
# nested field type is dict
is_complex, allow_json_failure = True, False
if is_complex:
try:
env_val = self.decode_complex_value(last_key, target_field, env_val)
env_val = self.decode_complex_value(last_key, target_field, env_val) # type: ignore
except ValueError as e:
if not allow_json_failure:
raise e
Expand Down
16 changes: 16 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2348,3 +2348,19 @@ class Settings(BaseSettings):

s = Settings(nested_foo=NestedSettings(fooAlias='EXAMPLE'))
assert s.model_dump() == {'nested_foo': {'foo': 'EXAMPLE'}}


def test_nested_models_as_dict_value(env):
class NestedSettings(BaseModel):
foo: Dict[str, int]

class Settings(BaseSettings):
nested: NestedSettings
sub_dict: Dict[str, NestedSettings]

model_config = SettingsConfigDict(env_nested_delimiter='__')

env.set('nested__foo', '{"a": 1}')
env.set('sub_dict__bar__foo', '{"b": 2}')
s = Settings()
assert s.model_dump() == {'nested': {'foo': {'a': 1}}, 'sub_dict': {'bar': {'foo': {'b': 2}}}}

0 comments on commit a853a13

Please sign in to comment.