Skip to content

Commit 6adc8b3

Browse files
committed
Support named tuples in Sequence validation
Backport of: #13978
1 parent 7637fbc commit 6adc8b3

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎pydantic/_internal/_validators.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from typing_inspection import typing_objects
2222

2323
from pydantic._internal._import_utils import import_cached_field_info
24+
from pydantic._internal._typing_extra import is_namedtuple
2425
from pydantic.errors import PydanticSchemaGenerationError
2526

2627

@@ -59,6 +60,8 @@ def sequence_validator(
5960
return v_list
6061
elif value_type is tuple:
6162
return tuple(v_list)
63+
elif is_namedtuple(value_type):
64+
return value_type(*v_list)
6265
else:
6366
# best guess at how to re-create the original type, more custom construction logic might be required
6467
return value_type(v_list) # type: ignore[call-arg]

‎tests/types/test_sequence.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from collections import deque
1+
from collections import deque, namedtuple
22
from collections.abc import Sequence
33
from typing import Any
44

@@ -201,3 +201,17 @@ class Model(BaseModel):
201201

202202
models = sequence_type([Model(a=1), Model(a=2)])
203203
assert ta.dump_python(ta.validate_python(models)) == sequence_type([{'a': 1}, {'a': 2}])
204+
205+
206+
def test_sequence_named_tuple() -> None:
207+
"""https://github.com/pydantic/pydantic/issues/13976"""
208+
209+
Point = namedtuple('Point', ['x', 'y'])
210+
211+
ta = TypeAdapter(Sequence[int])
212+
213+
assert ta.validate_python(Point(1, 2)) == Point(1, 2)
214+
assert ta.validate_python(Point('1', '2')) == Point(1, 2)
215+
216+
assert ta.dump_python(Point(1, 2)) == Point(1, 2)
217+
assert ta.dump_json(Point(1, 2)) == b'[1,2]'

0 commit comments

Comments
 (0)