Improve config validation for key_value_schemas (#49429)
This commit is contained in:
parent
ed9b199372
commit
45e1473f83
2 changed files with 9 additions and 9 deletions
|
@ -770,25 +770,25 @@ def deprecated(
|
|||
|
||||
|
||||
def key_value_schemas(
|
||||
key: str, value_schemas: dict[str, vol.Schema]
|
||||
) -> Callable[[Any], dict[str, Any]]:
|
||||
key: str, value_schemas: dict[Hashable, vol.Schema]
|
||||
) -> Callable[[Any], dict[Hashable, Any]]:
|
||||
"""Create a validator that validates based on a value for specific key.
|
||||
|
||||
This gives better error messages.
|
||||
"""
|
||||
|
||||
def key_value_validator(value: Any) -> dict[str, Any]:
|
||||
def key_value_validator(value: Any) -> dict[Hashable, Any]:
|
||||
if not isinstance(value, dict):
|
||||
raise vol.Invalid("Expected a dictionary")
|
||||
|
||||
key_value = value.get(key)
|
||||
|
||||
if key_value not in value_schemas:
|
||||
raise vol.Invalid(
|
||||
f"Unexpected value for {key}: '{key_value}'. Expected {', '.join(value_schemas)}"
|
||||
)
|
||||
if isinstance(key_value, Hashable) and key_value in value_schemas:
|
||||
return cast(Dict[Hashable, Any], value_schemas[key_value](value))
|
||||
|
||||
return cast(Dict[str, Any], value_schemas[key_value](value))
|
||||
raise vol.Invalid(
|
||||
f"Unexpected value for {key}: '{key_value}'. Expected {', '.join(str(key) for key in value_schemas)}"
|
||||
)
|
||||
|
||||
return key_value_validator
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue