Skip to content

Commit

Permalink
auto convert data type given annotations
Browse files Browse the repository at this point in the history
Signed-off-by: Zhiyuan Chen <[email protected]>
  • Loading branch information
ZhiyuanChen committed Aug 21, 2024
1 parent 060f166 commit e7c37b5
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
4 changes: 4 additions & 0 deletions chanfig/flat_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,10 @@ def set(self, name: Any, value: Any) -> None:
if name in self and isinstance(self.get(name), Variable):
self.get(name).set(value)
else:
if name in get_annotations(self):
anno = get_annotations(self)[name]
if isinstance(anno, type) and not isinstance(value, anno):
value = anno(value)
dict.__setitem__(self, name, value)

def __setitem__(self, name: Any, value: Any) -> None:
Expand Down
5 changes: 2 additions & 3 deletions tests/test_flat_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,8 @@ def test_validate(self):
ConfigDict(int_value=1, str_value="1", float_value=1.0)
with raises(TypeError):
ConfigDict(int_value="1", str_value="1", float_value=1.0)
with raises(TypeError):
self.dict.int_value = "1"
self.dict.validate()
self.dict.int_value = "1"
assert isinstance(self.dict.int_value, int)
ConfigDict(list_int=[1, 2, 3])
with raises(TypeError):
ConfigDict(list_int=[1, "2", 3])
Expand Down

0 comments on commit e7c37b5

Please sign in to comment.