validator.py: Extend functionality of check_dict().

With this commit, check_dict() can be used to verify
that all keys and/or values of a dict are of a certain
type.
This commit is contained in:
Robert Hönig 2018-01-07 18:55:39 +01:00
parent 82db9a211e
commit dcd62f92fb
1 changed files with 9 additions and 1 deletions

View File

@ -90,7 +90,8 @@ def check_list(sub_validator: Optional[Validator], length: Optional[int]=None) -
return None return None
return f return f
def check_dict(required_keys: Iterable[Tuple[str, Validator]], def check_dict(required_keys: Iterable[Tuple[str, Validator]]=[],
value_validator: Validator=None,
_allow_only_listed_keys: bool=False) -> Validator: _allow_only_listed_keys: bool=False) -> Validator:
def f(var_name: str, val: object) -> Optional[str]: def f(var_name: str, val: object) -> Optional[str]:
if not isinstance(val, dict): if not isinstance(val, dict):
@ -105,6 +106,13 @@ def check_dict(required_keys: Iterable[Tuple[str, Validator]],
if error: if error:
return error return error
if value_validator:
for key in val:
vname = '%s contains a value that' % (var_name,)
error = value_validator(vname, val[key])
if error:
return error
if _allow_only_listed_keys: if _allow_only_listed_keys:
delta_keys = set(val.keys()) - set(x[0] for x in required_keys) delta_keys = set(val.keys()) - set(x[0] for x in required_keys)
if len(delta_keys) != 0: if len(delta_keys) != 0: