Skip to content

Commit

Permalink
Support casting config values as dict with pydantic (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
percevalw committed Dec 15, 2023
1 parent 43c9281 commit 52c1faa
Show file tree
Hide file tree
Showing 2 changed files with 27 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
26 changes: 26 additions & 0 deletions confection/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1431,3 +1431,29 @@ 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 = 1
""")

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

0 comments on commit 52c1faa

Please sign in to comment.