Skip to content

Commit

Permalink
feat: support schema for NamedTuple
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Jan 21, 2021
1 parent 08868ab commit 0a1b719
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pydantic/annotated_types.py
Expand Up @@ -56,4 +56,4 @@ def create_model_from_namedtuple(namedtuple_cls: Type['NamedTuple'], **kwargs: A
field_definitions: Dict[str, Any] = {
field_name: (field_type, Required) for field_name, field_type in namedtuple_annotations.items()
}
return create_model(f'{namedtuple_cls.__name__}Model', **kwargs, **field_definitions)
return create_model(namedtuple_cls.__name__, **kwargs, **field_definitions)
1 change: 1 addition & 0 deletions pydantic/validators.py
Expand Up @@ -547,6 +547,7 @@ def make_namedtuple_validator(namedtuple_cls: Type[NamedTupleT]) -> Callable[[Tu
from .annotated_types import create_model_from_namedtuple

NamedTupleModel = create_model_from_namedtuple(namedtuple_cls)
namedtuple_cls.__pydantic_model__ = NamedTupleModel # type: ignore[attr-defined]

def namedtuple_validator(values: Tuple[Any, ...]) -> NamedTupleT:
dict_values: Dict[str, Any] = dict(zip(NamedTupleModel.__annotations__, values))
Expand Down
29 changes: 29 additions & 0 deletions tests/test_annotated_types.py
Expand Up @@ -58,6 +58,35 @@ class Model(BaseModel):
}
]

assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {
'pos': {'$ref': '#/definitions/Pos'},
'events': {'type': 'array', 'title': 'Events', 'items': {'$ref': '#/definitions/Event'}},
},
'required': ['pos', 'events'],
'definitions': {
'Pos': {
'type': 'object',
'title': 'Pos',
'properties': {'x': {'title': 'X'}, 'y': {'title': 'Y'}},
'required': ['x', 'y'],
},
'Event': {
'type': 'object',
'title': 'Event',
'properties': {
'a': {'title': 'A', 'type': 'integer'},
'b': {'title': 'B', 'type': 'integer'},
'c': {'title': 'C', 'type': 'integer'},
'd': {'title': 'D', 'type': 'string'},
},
'required': ['a', 'b', 'c', 'd'],
},
},
}


@pytest.mark.skipif(not TypedDict, reason='typing_extensions not installed')
def test_typeddict():
Expand Down

0 comments on commit 0a1b719

Please sign in to comment.