Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix error messages for Literal types with multiple allowed values #770

Merged
merged 2 commits into from Aug 21, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions HISTORY.rst
Expand Up @@ -3,6 +3,10 @@
History
-------

v0.32.3 (unreleased)
....................
* fix error messages for ``Literal`` types with multiple allowed values, #770 by @dmontagu

v0.32.2 (2019-08-17)
....................
* fix ``__post_init__`` usage with dataclass inheritance, fix #739 by @samuelcolvin
Expand Down
7 changes: 1 addition & 6 deletions pydantic/fields.py
Expand Up @@ -31,7 +31,6 @@
display_as_type,
is_literal_type,
lenient_issubclass,
literal_values,
sequence_like,
)
from .validators import NoneType, constant_validator, dict_validator, find_validators
Expand Down Expand Up @@ -197,11 +196,7 @@ def _populate_sub_fields(self) -> None: # noqa: C901 (ignore complexity)
# python 3.7 only, Pattern is a typing object but without sub fields
return
if is_literal_type(self.type_):
values = literal_values(self.type_)
if len(values) > 1:
self.type_ = Union[tuple(Literal[value] for value in values)]
else:
return
return
origin = getattr(self.type_, '__origin__', None)
if origin is None:
# field is not "typing" object eg. Union, Dict, List etc.
Expand Down
27 changes: 25 additions & 2 deletions pydantic/schema.py
Expand Up @@ -49,6 +49,7 @@
constr,
)
from .utils import (
Literal,
is_callable_type,
is_literal_type,
is_new_type,
Expand Down Expand Up @@ -758,8 +759,16 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
if is_new_type(field_type):
field_type = new_type_supertype(field_type)
if is_literal_type(field_type):
# If there were multiple literal values, field.sub_fields would not be falsy
literal_value = literal_values(field_type)[0]
values = literal_values(field_type)
if len(values) > 1:
return field_schema(
multivalue_literal_field_for_schema(values, field),
by_alias=by_alias,
model_name_map=model_name_map,
ref_prefix=ref_prefix,
known_models=known_models,
)
literal_value = values[0]
field_type = type(literal_value)
f_schema['const'] = literal_value
if issubclass(field_type, Enum):
Expand Down Expand Up @@ -807,6 +816,20 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
raise ValueError(f'Value not declarable with JSON Schema, field: {field}')


def multivalue_literal_field_for_schema(values: Tuple[Any, ...], field: Field) -> Field:
field = Field(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
field = Field(
return Field(

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my dreams of a one-commit pull request dashed

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry. 🙇‍♂️

I'll try to stop being such a pedant (pun intended).

name=field.name,
type_=Union[tuple(Literal[value] for value in values)],
class_validators=field.class_validators,
model_config=field.model_config,
default=field.default,
required=field.required,
alias=field.alias,
schema=field.schema,
)
return field


def encode_default(dft: Any) -> Any:
if isinstance(dft, (int, float, str)):
return dft
Expand Down
12 changes: 3 additions & 9 deletions tests/test_types.py
Expand Up @@ -1730,14 +1730,8 @@ class Model(BaseModel):
assert exc_info.value.errors() == [
{
'loc': ('a_or_b',),
'msg': "unexpected value; permitted: 'a'",
'msg': "unexpected value; permitted: 'a', 'b'",
'type': 'value_error.const',
'ctx': {'given': 'c', 'permitted': ('a',)},
},
{
'loc': ('a_or_b',),
'msg': "unexpected value; permitted: 'b'",
'type': 'value_error.const',
'ctx': {'given': 'c', 'permitted': ('b',)},
},
'ctx': {'given': 'c', 'permitted': ('a', 'b')},
}
]