Skip to content

Commit

Permalink
feat: add json support for NamedTuple
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Jan 21, 2021
1 parent 0a1b719 commit ee7033a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
14 changes: 12 additions & 2 deletions pydantic/main.py
Expand Up @@ -34,7 +34,15 @@
from .parse import Protocol, load_file, load_str_bytes
from .schema import default_ref_template, model_schema
from .types import PyObject, StrBytes
from .typing import AnyCallable, get_args, get_origin, is_classvar, resolve_annotations, update_field_forward_refs
from .typing import (
AnyCallable,
get_args,
get_origin,
is_classvar,
is_namedtuple,
resolve_annotations,
update_field_forward_refs,
)
from .utils import (
ROOT_KEY,
ClassAttribute,
Expand Down Expand Up @@ -732,7 +740,7 @@ def _get_value(
}

elif sequence_like(v):
return v.__class__(
seq_args = (
cls._get_value(
v_,
to_dict=to_dict,
Expand All @@ -748,6 +756,8 @@ def _get_value(
and (not value_include or value_include.is_included(i))
)

return v.__class__(*seq_args) if is_namedtuple(v.__class__) else v.__class__(seq_args)

elif isinstance(v, Enum) and getattr(cls.Config, 'use_enum_values', False):
return v.value

Expand Down
1 change: 1 addition & 0 deletions tests/test_annotated_types.py
Expand Up @@ -47,6 +47,7 @@ class Model(BaseModel):
assert model.pos == Position('1', 2)
assert model.events[0] == Event(1, 2, 3, 'qwe')
assert repr(model) == "Model(pos=Pos(x='1', y=2), events=[Event(a=1, b=2, c=3, d='qwe')])"
assert model.json() == '{"pos": ["1", 2], "events": [[1, 2, 3, "qwe"]]}'

with pytest.raises(ValidationError) as exc_info:
Model(pos=('1', 2), events=[['qwe', '2', 3, 'qwe']])
Expand Down

0 comments on commit ee7033a

Please sign in to comment.