diff --git a/pydantic/main.py b/pydantic/main.py index 786ee22969..ae99eef9d3 100644 --- a/pydantic/main.py +++ b/pydantic/main.py @@ -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, @@ -732,7 +740,7 @@ def _get_value( } elif sequence_like(v): - return v.__class__( + seq_args = ( cls._get_value( v_, to_dict=to_dict, @@ -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 diff --git a/tests/test_annotated_types.py b/tests/test_annotated_types.py index aa29909e8d..1bae70d9bf 100644 --- a/tests/test_annotated_types.py +++ b/tests/test_annotated_types.py @@ -3,6 +3,7 @@ - NamedTuple - TypedDict """ +import json import sys from collections import namedtuple from typing import List, NamedTuple, Tuple @@ -47,6 +48,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() == json.dumps(model.dict()) == '{"pos": ["1", 2], "events": [[1, 2, 3, "qwe"]]}' with pytest.raises(ValidationError) as exc_info: Model(pos=('1', 2), events=[['qwe', '2', 3, 'qwe']])