Skip to content

Commit

Permalink
Fixed literal validator errors for unhashable values (#6194)
Browse files Browse the repository at this point in the history
  • Loading branch information
markus1978 committed Jun 20, 2023
1 parent ccedd74 commit d7afe99
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions changes/6188-markus1978.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed literal validator errors for unhashable values.
2 changes: 1 addition & 1 deletion pydantic/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ def make_literal_validator(type_: Any) -> Callable[[Any], Any]:
def literal_validator(v: Any) -> Any:
try:
return allowed_choices[v]
except KeyError:
except (KeyError, TypeError):
raise errors.WrongConstantError(given=v, permitted=permitted_choices)

return literal_validator
Expand Down
18 changes: 18 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1189,6 +1189,24 @@ class Model(BaseModel):
]


def test_literal_validator_non_str_value():
class Model(BaseModel):
a: Literal['foo']

Model(a='foo')

with pytest.raises(ValidationError) as exc_info:
Model(a={'bar': 'foo'})
assert exc_info.value.errors() == [
{
'loc': ('a',),
'msg': "unexpected value; permitted: 'foo'",
'type': 'value_error.const',
'ctx': {'given': {'bar': 'foo'}, 'permitted': ('foo',)},
}
]


def test_literal_validator_str_enum():
class Bar(str, Enum):
FIZ = 'fiz'
Expand Down

0 comments on commit d7afe99

Please sign in to comment.