Skip to content

Commit

Permalink
Fixed literal validator errors for unhashable values (#6188)
Browse files Browse the repository at this point in the history
  • Loading branch information
markus1978 committed Jun 20, 2023
1 parent ccedd74 commit 91208b6
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
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.
3 changes: 3 additions & 0 deletions pydantic/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,9 @@ def make_literal_validator(type_: Any) -> Callable[[Any], Any]:
allowed_choices = {v: v for v in permitted_choices}

def literal_validator(v: Any) -> Any:
if not isinstance(v, Hashable):
raise errors.WrongConstantError(given=str(v), permitted=permitted_choices)

try:
return allowed_choices[v]
except KeyError:
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': str({'bar': 'foo'}), 'permitted': ('foo',)},
}
]


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

0 comments on commit 91208b6

Please sign in to comment.