Skip to content

Commit

Permalink
Support casting config values as dict with pydantic (explosion#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
percevalw committed Dec 19, 2023
1 parent 43c9281 commit cbd7f90
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion confection/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -960,7 +960,7 @@ def _update_from_parsed(
filled[key] = value
if key not in final:
final[key] = value
if isinstance(value, dict):
if isinstance(value, dict) and isinstance(final[key], dict):
filled[key], final[key] = cls._update_from_parsed(
value, filled[key], final[key]
)
Expand Down
28 changes: 28 additions & 0 deletions confection/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1431,3 +1431,31 @@ def test_parse_strings_interpretable_as_ints():
)
assert cfg["a"]["foo"] == [3, "003", "y"]
assert cfg["b"]["bar"] == 3


def test_dict_casting():
class CastStrAsDict:
@classmethod
def validate(cls, value):
if isinstance(value, str):
return {value: True}
return value

@classmethod
def __get_validators__(cls):
yield cls.validate

class SectionSchema(BaseModel):
key: CastStrAsDict

class MainSchema(BaseModel):
section: SectionSchema

cfg = Config().from_str(
"""\
[section]
key = "ok"
"""
)

assert my_registry.fill(cfg, schema=MainSchema) == {"section": {"key": "ok"}}

0 comments on commit cbd7f90

Please sign in to comment.