Skip to content

Commit 37e0538

Browse files
committed
Support casting config values as dict with pydantic (explosion#54)
1 parent 43c9281 commit 37e0538

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

confection/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -960,7 +960,7 @@ def _update_from_parsed(
960960
filled[key] = value
961961
if key not in final:
962962
final[key] = value
963-
if isinstance(value, dict):
963+
if isinstance(value, dict) and isinstance(final[key], dict):
964964
filled[key], final[key] = cls._update_from_parsed(
965965
value, filled[key], final[key]
966966
)

confection/tests/test_config.py

+26
Original file line numberDiff line numberDiff line change
@@ -1431,3 +1431,29 @@ def test_parse_strings_interpretable_as_ints():
14311431
)
14321432
assert cfg["a"]["foo"] == [3, "003", "y"]
14331433
assert cfg["b"]["bar"] == 3
1434+
1435+
1436+
def test_dict_casting():
1437+
class CastStrAsDict:
1438+
@classmethod
1439+
def validate(cls, value):
1440+
if isinstance(value, str):
1441+
return {value: True}
1442+
return value
1443+
1444+
@classmethod
1445+
def __get_validators__(cls):
1446+
yield cls.validate
1447+
1448+
class SectionSchema(BaseModel):
1449+
key: CastStrAsDict
1450+
1451+
class MainSchema(BaseModel):
1452+
section: SectionSchema
1453+
1454+
cfg = Config().from_str("""
1455+
[section]
1456+
key = 1
1457+
""")
1458+
1459+
assert my_registry.fill(cfg, schema=MainSchema) == {'section': {'key': 1}}

0 commit comments

Comments
 (0)