Backtestspydanticrun-20261005-183002#12529
Preserve NamedTuple class during validation
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Patch A fixes the root cause with a small change in `CallValidator`. When the call target is a class and a smart union is tracking exactness, an input that is an exact instance of that class is marked `Exact`. Any other input is capped at `Strict`. As a result, `B(x=1)` validated against `A | B` stays a `B`, in both lax and strict config. Non-instance inputs still pick left-to-right, a single-type field still converts `B` to `A`, and instance fields are still revalidated (`B('1')` becomes `B(1)`). Its tests cover these cases in pydantic-core and in pydantic for both `typing.NamedTuple` and `collections.namedtuple`, and the core assertions would fail before the change. Existing behaviour outside smart unions is left alone.
Patch B also fixes the union case: its new validator floors non-instance inputs to `Strict` and leaves exact instances untouched. To get there, it replaces the whole namedtuple implementation with a new `named-tuple` core schema, validator, serializer and error type. That carries many user-visible behaviour changes beyond the issue:
- Error types and locations change (`too_long` instead of `unexpected_positional_argument`, `extra_forbidden` instead of `unexpected_keyword_argument`).
- The `arguments_type` docs are rewritten.
- JSON schema output changes (the existing modify-schema test was rewritten, and its expected object schema became an array schema).
- The `pydantic_js_prefer_positional_arguments` metadata hook no longer applies.
- Serialization and union serialization are now handled by new code.
- The existing test file is deleted and recreated with changed expectations.
This broad redesign adds substantial regression and compatibility risk and obscures the actual fix. Both patches resolve the issue, but A does so with far less risk and with focused tests.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
14m 29s
Wall-clock time in the container
Full test suite
No new failures
12,304 passed · 499 skipped · 12,803 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
121vs 1,755 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
This is what I'm observing:
import pydantic
from typing import NamedTuple
class A(NamedTuple):
x: int
class B(NamedTuple):
x: int
class C(pydantic.BaseModel):
a_or_b: A | B
c = C(a_or_b=B(x=1))
print(c)
# expected: a_or_b=B(x=1)
# prints: a_or_b=A(x=1)
This short-circuits on type arguments in the union in order in the smart mode of unions (left_to_right I assume makes no difference, the problem lies in exactness).
If we reverse it, the output will show B because B was first that structurally matched.
It works this way in strict mode too.
This resembles left_to_right more than smart mode of the union schema.
Conceptually, Pydantic looks for ways to match namedtuple as a structural type, whereas the nominal bit was missed.
This applies to old-fashion named tuples as well:
from collections import namedtuple
import pydantic
A = namedtuple('A', 'x')
B = namedtuple('B', 'x')
class C(pydantic.BaseModel):
a_or_b: A | B
c = C(a_or_b=B(x=1))
print(c) # a_or_b=A(x=1)
We would want to convert between uniform namedtuples in non-strict mode -- sure:
import pydantic
from typing import NamedTuple
class A(NamedTuple):
x: int
class B(NamedTuple):
x: int
class C(pydantic.BaseModel):
only_a: A
c = C(only_a=B(x=1))
print(c) # only_a=A(x=1)
but I'm not so sure we want the union schema to miss the nominal type of the input. If we can preserve the original type, my instinct is that we'd want to keep it. Esp. since we don't observe this behavior with dataclasses (namedtuples are of quite different nature, though).
The current behavior can be interpreted as a feature, not a bug -- feel free to relabel this as a feature request if you do think that's true.
In short
I'm proposing a feature to, in validation, validate every namedtuple input against its targeted namedtuple class (so, return_schema -- seems like return_schema isn't used by namedtuple schemas yet) before proceeding with the call validator logic and deconstructing it as a collection of arguments and trying a call to the namedtuple constructor. It would be based on a new idempotent flag in CallValidator -- if a function call is idempotent, the validation should start from the return validator -- if that doesn't pass, only then try to call. As a result, nominal types wouldn't be swapped in unions of namedtuples in smart union mode.
Do you guys think this is worth adding to pydantic, or too much hassle for an edge case?
Thanks!
PS One more thing. This relies on the assumption that instance checks guarantees type safety of the object's state.
If the namedtuple instance contains unsound data, its internals wouldn't be re-validated and fixed up in place as it happens right now. In this sense, the change could be breaking.
The same that would happen here already happens for dataclasses in Pydantic:
from dataclasses import dataclass
from pydantic import BaseModel
@dataclass
class Foo:
x: int
malformed = Foo(x="1")
class Model(BaseModel):
foo: Foo
print(Model(foo=malformed))
If someone has an unsure instance of a namedtuple, they would need to re-validate it through type adapter, perhaps.
Or just use models directly on raw data -- for 99.999% of people this won't happen.
Python, Pydantic & OS Version
❯ python -c "import pydantic.version; print(pydantic.version.version_info())"
pydantic version: 2.13.0a0+dev
pydantic-core version: 2.41.5
pydantic-core build: profile=debug pgo=false
python version: 3.14.0rc3 (main, Sep 18 2025, 19:47:22) [Clang 20.1.4 ]
platform: Linux-6.16.12-200.fc42.x86_64-x86_64-with-glibc2.41
related packages: typing_extensions-4.14.1
commit: f42171c76The two patches
pydantic-core/src/validators/call.rsindex afd40dd9..810e27fe 100644@@ -4,14 +4,14 @@ use pyo3::exceptions::PyTypeError; use pyo3::intern; use pyo3::prelude::*; use pyo3::types::PyString;-use pyo3::types::{PyDict, PyTuple};+use pyo3::types::{PyDict, PyTuple, PyType}; use crate::errors::ValResult; use crate::input::Input; use crate::tools::SchemaDict; -use super::validation_state::ValidationState;+use super::validation_state::{Exactness, ValidationState}; use super::{BuildValidator, CombinedValidator, DefinitionsBuilder, Validator, build_validator}; #[derive(Debug)]@@ -82,6 +82,41 @@ impl Validator for CallValidator { py: Python<'py>, input: &(impl Input<'py> + ?Sized), state: &mut ValidationState<'_, 'py>,+ ) -> ValResult<Py<PyAny>> {+ // When the function is a class (e.g. a `NamedTuple`) and we're tracking exactness (in a smart union),+ // an input which is already an instance of exactly that class is an exact match, even if its fields+ // need to be coerced during revalidation. Constructing a new instance from anything else is at best+ // a strict match. This lets smart unions preserve the class of the input, e.g. `B(x=1)` validated+ // against `A | B` stays a `B` rather than being converted to an `A`.+ let (Ok(class), Some(outer_exactness)) = (self.function.bind(py).cast::<PyType>(), state.exactness) else {+ return self.validate_call(py, input, state);+ };+ let is_exact_instance = input.as_python().is_some_and(|py_input| py_input.is_exact_instance(class));++ state.exactness = Some(Exactness::Exact);+ let result = self.validate_call(py, input, state);+ let inner_exactness = state.exactness.unwrap_or(Exactness::Lax);+ state.exactness = Some(outer_exactness);++ state.floor_exactness(if is_exact_instance {+ Exactness::Exact+ } else {+ inner_exactness.min(Exactness::Strict)+ });+ result+ }++ fn get_name(&self) -> &str {+ &self.name+ }+}++impl CallValidator {+ fn validate_call<'py>(+ &self,+ py: Python<'py>,+ input: &(impl Input<'py> + ?Sized),+ state: &mut ValidationState<'_, 'py>, ) -> ValResult<Py<PyAny>> { let args = self.arguments_validator.validate(py, input, state)?.into_bound(py); @@ -102,8 +137,4 @@ impl Validator for CallValidator { Ok(return_value) } }-- fn get_name(&self) -> &str {- &self.name- } }pydantic-core/tests/validators/test_call.pyindex eb25f132..707eae53 100644@@ -209,3 +209,24 @@ def test_custom_name(): assert 'name:"call[foobar]"' in plain_repr(v) assert v.validate_python((1,)) == 1 assert v.validate_python(('2',)) == 2+++def test_named_tuple_smart_union_preserves_class():+ A = namedtuple('A', 'x')+ B = namedtuple('B', 'x')++ def nt_schema(cls):+ return cs.call_schema(+ arguments=cs.arguments_schema(arguments=[cs.arguments_parameter(name='x', schema=cs.int_schema())]),+ function=cls,+ )++ v = SchemaValidator(cs.union_schema([nt_schema(A), nt_schema(B)]))+ assert type(v.validate_python(B(1))) is B+ assert type(v.validate_python(A(1))) is A+ # non-instance input still picks the first matching member+ assert type(v.validate_python((1,))) is A+ # an instance of the exact class wins even if its fields need lax coercion+ validated = v.validate_python(B('1'))+ assert type(validated) is B+ assert validated == B(1)tests/test_types_namedtuple.pyindex 7c72db4d..46680e6b 100644@@ -254,3 +254,60 @@ def test_namedtuple_inheritance_with_annotations(): 'input': 'c', } ]+++class _UnionA(NamedTuple):+ x: int+++class _UnionB(NamedTuple):+ x: int+++_UnionOldA = namedtuple('_UnionOldA', 'x')+_UnionOldB = namedtuple('_UnionOldB', 'x')+++@pytest.mark.parametrize('strict', [False, True])+@pytest.mark.parametrize(+ 'nt_a,nt_b',+ [(_UnionA, _UnionB), (_UnionOldA, _UnionOldB)],+ ids=['typing.NamedTuple', 'collections.namedtuple'],+)+def test_namedtuple_union_preserves_input_class(nt_a, nt_b, strict: bool) -> None:+ """Smart unions of namedtuples should keep the class of a namedtuple instance input."""++ class Model(BaseModel):+ model_config = ConfigDict(strict=strict)++ a_or_b: nt_a | nt_b+ b_or_a: nt_b | nt_a++ m = Model(a_or_b=nt_b(x=1), b_or_a=nt_a(x=1))+ assert type(m.a_or_b) is nt_b+ assert type(m.b_or_a) is nt_a+ assert m.a_or_b == nt_b(x=1)++ m = Model(a_or_b=nt_a(x=1), b_or_a=nt_b(x=1))+ assert type(m.a_or_b) is nt_a+ assert type(m.b_or_a) is nt_b+++def test_namedtuple_union_instance_still_revalidated() -> None:+ m = TypeAdapter(_UnionA | _UnionB).validate_python(_UnionB(x='1'))+ assert type(m) is _UnionB+ assert m.x == 1+++def test_namedtuple_union_non_instance_input_left_to_right() -> None:+ ta = TypeAdapter(_UnionA | _UnionB)+ assert type(ta.validate_python((1,))) is _UnionA+ assert type(ta.validate_python({'x': 1})) is _UnionA+ assert type(ta.validate_json('[1]')) is _UnionA+++def test_namedtuple_single_type_converts_other_namedtuple() -> None:+ class Model(BaseModel):+ only_a: _UnionA++ assert type(Model(only_a=_UnionB(x=1)).only_a) is _UnionA
docs/api/standard_library_types.mdindex 4739bdb4c..0677fd0f4 100644@@ -880,6 +880,7 @@ Standard library type: [`typing.NamedTuple`][] (and types created by the [`colle * Allows [`tuple`][] and [`list`][] instances. Validate each item according to the field definition. * Allows [`dict`][] instances. Keys must match the named tuple field names, and values are validated according to the field definition.+* Allows instances of the named tuple class (fields are revalidated). <h4>Serialization</h4> docs/errors/validation_errors.mdindex fc0539fef..bdc536ea8 100644@@ -8,25 +8,19 @@ see [Troubleshooting Validation Errors](troubleshooting.md). ## `arguments_type` This error is raised when an object that would be passed as arguments to a function during validation is not-a `tuple`, `list`, or `dict`. Because `NamedTuple` uses function calls in its implementation, that is one way to-produce this error:+a `tuple`, `list`, or `dict`: ```python-from typing import NamedTuple--from pydantic import BaseModel, ValidationError-+from pydantic import TypeAdapter, ValidationError -class MyNamedTuple(NamedTuple):- x: int +def func(x: int) -> None: ... -class MyModel(BaseModel):- field: MyNamedTuple +ta = TypeAdapter(func) try:- MyModel.model_validate({'field': 'invalid'})+ ta.validate_python('invalid') except ValidationError as exc: print(repr(exc.errors()[0]['type'])) #> 'arguments_type'@@ -1602,6 +1596,32 @@ except ValidationError as exc: #> 'multiple_of' ``` +## `named_tuple_type`++This error is raised when the input value is not valid for a named tuple field:++```python+from typing import NamedTuple++from pydantic import BaseModel, ValidationError+++class Point(NamedTuple):+ x: int+ y: int+++class Model(BaseModel):+ p: Point+++try:+ Model(p='invalid')+except ValidationError as exc:+ print(repr(exc.errors()[0]['type']))+ #> 'named_tuple_type'+```+ ## `needs_python_object` This type of error is raised when validation is attempted from a format that cannot be converted to a Python object.docs/plugins/conversion_table.pyindex 4f8e86b3f..927312b86 100644@@ -910,84 +910,98 @@ table_rows: list[Row] = [ typing.NamedTuple, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( typing.NamedTuple, 'Array', strict=True, json_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema],+ ),+ Row(+ typing.NamedTuple,+ 'Object',+ strict=True,+ json_input=True,+ core_schemas=[core_schema.NamedTupleSchema], ), Row( typing.NamedTuple, collections.namedtuple, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( typing.NamedTuple, tuple, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( typing.NamedTuple, list, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( typing.NamedTuple, dict, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( collections.namedtuple, collections.namedtuple, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( collections.namedtuple, 'Array', strict=True, json_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema],+ ),+ Row(+ collections.namedtuple,+ 'Object',+ strict=True,+ json_input=True,+ core_schemas=[core_schema.NamedTupleSchema], ), Row( collections.namedtuple, typing.NamedTuple, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( collections.namedtuple, tuple, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( collections.namedtuple, list, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( collections.namedtuple, dict, strict=True, python_input=True,- core_schemas=[core_schema.CallSchema],+ core_schemas=[core_schema.NamedTupleSchema], ), Row( Sequence,pydantic-core/python/pydantic_core/core_schema.pyindex 965cf28e1..85f6a8c04 100644@@ -3589,6 +3589,112 @@ def dataclass_schema( ) +class NamedTupleField(TypedDict, total=False):+ type: Required[Literal['named-tuple-field']]+ name: Required[str]+ schema: Required[CoreSchema]+ validation_alias: str | list[str | int] | list[list[str | int]]+ metadata: dict[str, Any]+++def named_tuple_field(+ name: str,+ schema: CoreSchema,+ *,+ validation_alias: str | list[str | int] | list[list[str | int]] | None = None,+ metadata: dict[str, Any] | None = None,+) -> NamedTupleField:+ """+ Returns a schema for a named tuple field, e.g.:++ ```py+ from pydantic_core import core_schema++ field = core_schema.named_tuple_field(name='x', schema=core_schema.int_schema())+ ```++ Args:+ name: The name of the field+ schema: The schema to use for the field+ validation_alias: The alias(es) to use to find the field in the validation data, only used+ when validating from a dictionary or mapping+ metadata: Any other information you want to include with the schema, not used by pydantic-core+ """+ return _dict_not_none(+ type='named-tuple-field',+ name=name,+ schema=schema,+ validation_alias=validation_alias,+ metadata=metadata,+ )+++class NamedTupleSchema(TypedDict, total=False):+ type: Required[Literal['named-tuple']]+ cls: Required[type[Any]]+ fields: Required[list[NamedTupleField]]+ cls_name: str+ ref: str+ metadata: dict[str, Any]+ serialization: SerSchema+++def named_tuple_schema(+ cls: type[Any],+ fields: list[NamedTupleField],+ *,+ cls_name: str | None = None,+ ref: str | None = None,+ metadata: dict[str, Any] | None = None,+ serialization: SerSchema | None = None,+) -> NamedTupleSchema:+ """+ Returns a schema for a named tuple, e.g.:++ ```py+ from typing import NamedTuple++ from pydantic_core import SchemaValidator, core_schema++ class Point(NamedTuple):+ x: int+ y: int++ schema = core_schema.named_tuple_schema(+ Point,+ [+ core_schema.named_tuple_field(name='x', schema=core_schema.int_schema()),+ core_schema.named_tuple_field(name='y', schema=core_schema.int_schema()),+ ],+ )+ v = SchemaValidator(schema)+ assert v.validate_python((1, '2')) == Point(x=1, y=2)+ ```++ Fields are validated positionally when the input is a (named) tuple, list or JSON array,+ and by name when the input is a dictionary, mapping or JSON object. Instances of `cls`+ always revalidate. Strict mode is currently ignored, matching the behavior of the+ `'call'` core schema previously used for named tuples.++ Args:+ cls: The named tuple class, used to construct instances and perform instance checks+ fields: The fields to use for the named tuple, in order+ cls_name: The name to use in error locs, etc; this is useful for generics (default: `cls.__name__`)+ ref: optional unique identifier of the schema, used to reference the schema in other places+ metadata: Any other information you want to include with the schema, not used by pydantic-core+ serialization: Custom serialization schema+ """+ return _dict_not_none(+ type='named-tuple',+ cls=cls,+ fields=fields,+ cls_name=cls_name,+ ref=ref,+ metadata=metadata,+ serialization=serialization,+ )++ class ArgumentsParameter(TypedDict, total=False): name: Required[str] schema: Required[CoreSchema]@@ -4247,6 +4353,7 @@ if not MYPY: | ModelSchema | DataclassArgsSchema | DataclassSchema+ | NamedTupleSchema | ArgumentsSchema | ArgumentsV3Schema | CallSchema@@ -4308,6 +4415,7 @@ CoreSchemaType: TypeAlias = Literal[ 'model', 'dataclass-args', 'dataclass',+ 'named-tuple', 'arguments', 'arguments-v3', 'call',@@ -4321,7 +4429,9 @@ CoreSchemaType: TypeAlias = Literal[ 'complex', ] -CoreSchemaFieldType: TypeAlias = Literal['model-field', 'dataclass-field', 'typed-dict-field', 'computed-field']+CoreSchemaFieldType: TypeAlias = Literal[+ 'model-field', 'dataclass-field', 'typed-dict-field', 'named-tuple-field', 'computed-field'+] # used in _pydantic_core.pyi::PydanticKnownError@@ -4342,6 +4452,7 @@ ErrorType: TypeAlias = Literal[ 'model_attributes_type', 'dataclass_type', 'dataclass_exact_type',+ 'named_tuple_type', 'default_factory_not_called', 'none_required', 'greater_than',pydantic-core/src/errors/types.rsindex 8f8e936ce..748d2d5bf 100644@@ -198,6 +198,11 @@ error_types! { class_name: {ctx_type: String, ctx_fn: field_from_context}, }, // ---------------------+ // namedtuple errors+ NamedTupleType {+ class_name: {ctx_type: String, ctx_fn: field_from_context},+ },+ // --------------------- // Default factory not called (happens when there's already an error and the factory takes data) DefaultFactoryNotCalled {}, // ---------------------@@ -504,6 +509,7 @@ impl ErrorType { Self::ModelAttributesType { .. } => "Input should be a valid dictionary or object to extract fields from", Self::DataclassType { .. } => "Input should be a dictionary or an instance of {class_name}", Self::DataclassExactType { .. } => "Input should be an instance of {class_name}",+ Self::NamedTupleType { .. } => "Input should be a tuple, list, dictionary or an instance of {class_name}", Self::DefaultFactoryNotCalled { .. } => { "The default factory uses validated data, but at least one validation error occurred" }@@ -634,6 +640,7 @@ impl ErrorType { | Self::ModelAttributesType { .. } | Self::DictType { .. } | Self::DataclassType { .. } => "Input should be an object",+ Self::NamedTupleType { .. } => "Input should be an array or an object", Self::TimeDeltaType { .. } => "Input should be a valid duration", Self::TimeDeltaParsing { .. } => "Input should be a valid duration, {error}", Self::ArgumentsType { .. } => "Arguments must be an array or an object",@@ -687,7 +694,8 @@ impl ErrorType { Self::NeedsPythonObject { method_name, .. } => render!(tmpl, method_name), Self::ModelType { class_name, .. } | Self::DataclassType { class_name, .. }- | Self::DataclassExactType { class_name, .. } => render!(tmpl, class_name),+ | Self::DataclassExactType { class_name, .. }+ | Self::NamedTupleType { class_name, .. } => render!(tmpl, class_name), Self::GreaterThan { gt, .. } => to_string_render!(tmpl, gt), Self::GreaterThanEqual { ge, .. } => to_string_render!(tmpl, ge), Self::LessThan { lt, .. } => to_string_render!(tmpl, lt),pydantic-core/src/serializers/shared.rsindex f6342c1ec..baf2dcc07 100644@@ -159,6 +159,7 @@ combined_serializer! { Tuple: super::type_serializers::tuple::TupleSerializer; Complex: super::type_serializers::complex::ComplexSerializer; TypedDict: super::type_serializers::typed_dict::TypedDictSerializer;+ NamedTuple: super::type_serializers::named_tuple::NamedTupleSerializer; } } @@ -393,6 +394,7 @@ impl PyGcTraverse for CombinedSerializer { CombinedSerializer::Uuid(inner) => inner.py_gc_traverse(visit), CombinedSerializer::Complex(inner) => inner.py_gc_traverse(visit), CombinedSerializer::TypedDict(inner) => inner.py_gc_traverse(visit),+ CombinedSerializer::NamedTuple(inner) => inner.py_gc_traverse(visit), CombinedSerializer::PolymorphismTrampoline(inner) => inner.py_gc_traverse(visit), } }pydantic-core/src/serializers/type_serializers/mod.rsindex ad664e8f8..0fea0fb00 100644@@ -19,6 +19,7 @@ pub mod list; pub mod literal; pub mod missing_sentinel; pub mod model;+pub mod named_tuple; pub mod nullable; pub mod other; pub mod set_frozenset;pydantic-core/src/serializers/type_serializers/named_tuple.rsnew file mode 100644index 000000000..b27d44744@@ -0,0 +1,235 @@+use std::borrow::Cow;+use std::sync::Arc;++use pyo3::intern;+use pyo3::prelude::*;+use pyo3::types::{PyDict, PyList, PyTuple, PyType};++use serde::ser::SerializeSeq;++use crate::PydanticSerializationUnexpectedValue;+use crate::build_tools::py_schema_error_type;+use crate::definitions::DefinitionsBuilder;+use crate::serializers::SerializationState;+use crate::serializers::extra::IncludeExclude;+use crate::serializers::extra::SerCheck;+use crate::tools::SchemaDict;++use super::tuple::KeyBuilder;+use super::{+ BuildSerializer, CombinedSerializer, PydanticSerializer, SchemaFilter, SerMode, TypeSerializer, infer_json_key,+ infer_serialize, infer_to_python, py_err_se_err,+};++#[derive(Debug)]+pub struct NamedTupleSerializer {+ class: Py<PyType>,+ serializers: Vec<Arc<CombinedSerializer>>,+ filter: SchemaFilter<usize>,+ name: String,+}++impl BuildSerializer for NamedTupleSerializer {+ const EXPECTED_TYPE: &'static str = "named-tuple";++ fn build(+ schema: &Bound<'_, PyDict>,+ config: Option<&Bound<'_, PyDict>>,+ definitions: &mut DefinitionsBuilder<Arc<CombinedSerializer>>,+ ) -> PyResult<Arc<CombinedSerializer>> {+ let py = schema.py();++ let class = schema.get_as_req::<Bound<'_, PyType>>(intern!(py, "cls"))?;+ let name = match schema.get_as::<String>(intern!(py, "cls_name"))? {+ Some(name) => name,+ None => class.getattr(intern!(py, "__name__"))?.extract()?,+ };++ let fields_list: Bound<'_, PyList> = schema.get_as_req(intern!(py, "fields"))?;+ let mut serializers: Vec<Arc<CombinedSerializer>> = Vec::with_capacity(fields_list.len());++ for field in fields_list {+ let field = field.cast::<PyDict>()?;+ let field_name: String = field.get_as_req(intern!(py, "name"))?;+ let field_schema = field.get_as_req(intern!(py, "schema"))?;+ let serializer = CombinedSerializer::build(&field_schema, config, definitions)+ .map_err(|e| py_schema_error_type!("Field `{field_name}`:\n {e}"))?;+ serializers.push(serializer);+ }++ Ok(CombinedSerializer::NamedTuple(Self {+ class: class.into(),+ serializers,+ filter: SchemaFilter::from_schema(schema)?,+ name,+ })+ .into())+ }+}++impl_py_gc_traverse!(NamedTupleSerializer { class, serializers });++impl TypeSerializer for NamedTupleSerializer {+ fn to_python<'py>(&self, value: &Bound<'py, PyAny>, state: &mut SerializationState<'py>) -> PyResult<Py<PyAny>> {+ match self.tuple_value(value, state)? {+ Some(py_tuple) => {+ let py = value.py();++ let mut items = Vec::with_capacity(py_tuple.len());++ self.for_each_item_and_serializer(&py_tuple, state, |entry| {+ entry+ .serializer+ .to_python(&entry.item, entry.state)+ .map(|item| items.push(item))+ })??;++ match state.extra.mode {+ SerMode::Json => Ok(PyList::new(py, items)?.into()),+ _ => Ok(PyTuple::new(py, items)?.into()),+ }+ }+ None => {+ state.warn_fallback_py(&self.name, value)?;+ infer_to_python(value, state)+ }+ }+ }++ fn json_key<'a, 'py>(+ &self,+ key: &'a Bound<'py, PyAny>,+ state: &mut SerializationState<'py>,+ ) -> PyResult<Cow<'a, str>> {+ match self.tuple_value(key, state)? {+ Some(py_tuple) => {+ let mut key_builder = KeyBuilder::new();++ let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+ self.for_each_item_and_serializer(&py_tuple, state, |entry| {+ entry+ .serializer+ .json_key(&entry.item, entry.state)+ .map(|key| key_builder.push(&key))+ })??;++ Ok(Cow::Owned(key_builder.finish()))+ }+ None => {+ state.warn_fallback_py(&self.name, key)?;+ infer_json_key(key, state)+ }+ }+ }++ fn serde_serialize<'py, S: serde::ser::Serializer>(+ &self,+ value: &Bound<'py, PyAny>,+ serializer: S,+ state: &mut SerializationState<'py>,+ ) -> Result<S::Ok, S::Error> {+ match self.tuple_value(value, state).map_err(py_err_se_err)? {+ Some(py_tuple) => {+ let mut seq = serializer.serialize_seq(Some(py_tuple.len()))?;++ self.for_each_item_and_serializer(&py_tuple, state, |entry| {+ seq.serialize_element(&PydanticSerializer::new(&entry.item, entry.serializer, entry.state))+ })+ .map_err(py_err_se_err)??;++ seq.end()+ }+ None => {+ state.warn_fallback_ser::<S>(&self.name, value)?;+ infer_serialize(value, serializer, state)+ }+ }+ }++ fn get_name(&self) -> &str {+ &self.name+ }++ fn retry_with_lax_check(&self) -> bool {+ true+ }+}++struct NamedTupleSerializerEntry<'a, 'py> {+ item: Bound<'py, PyAny>,+ serializer: &'a CombinedSerializer,+ state: &'a mut SerializationState<'py>,+}++impl NamedTupleSerializer {+ /// Extract the value as a tuple, if possible.+ ///+ /// In strict check mode (e.g. when serializing a union), the value is required to be an+ /// instance of the named tuple class, so that the nominal class is preserved. In lax check+ /// mode, any tuple is accepted.+ fn tuple_value<'py>(+ &self,+ value: &Bound<'py, PyAny>,+ state: &SerializationState<'py>,+ ) -> PyResult<Option<Bound<'py, PyTuple>>> {+ if state.check == SerCheck::Strict && !value.is_instance(self.class.bind(value.py()))? {+ return Ok(None);+ }+ Ok(value.cast::<PyTuple>().ok().map(Bound::to_owned))+ }++ /// Try to serialize each item in the tuple with the corresponding field serializer.+ ///+ /// If the tuple doesn't match the number of fields, in strict check mode, an error is+ /// returned; otherwise a warning is emitted and extra items are dropped.+ fn for_each_item_and_serializer<'py, E>(+ &self,+ tuple: &Bound<'py, PyTuple>,+ state: &mut SerializationState<'py>,+ mut f: impl for<'a> FnMut(NamedTupleSerializerEntry<'a, 'py>) -> Result<(), E>,+ ) -> PyResult<Result<(), E>> {+ let n_items = tuple.len();++ if state.check != SerCheck::None && n_items != self.serializers.len() {+ return Err(PydanticSerializationUnexpectedValue::new_from_msg(Some(format!(+ "Expected {} items, but got {}",+ self.serializers.len(),+ n_items+ )))+ .to_py_err());+ }++ let mut py_tuple_iter = tuple.iter();++ for (index, serializer) in self.serializers.iter().enumerate() {+ let Some(element) = py_tuple_iter.next() else {+ state+ .warnings+ .register_warning(PydanticSerializationUnexpectedValue::new_from_msg(Some(+ "Unexpected too few items present in named tuple".to_string(),+ )));+ break;+ };+ if let Some(next_include_exclude) = self.filter.index_filter(index, state, Some(n_items))? {+ let state = &mut state.scoped_include_exclude(next_include_exclude);+ if let Err(e) = f(NamedTupleSerializerEntry {+ item: element,+ serializer,+ state,+ }) {+ return Ok(Err(e));+ }+ }+ }++ if py_tuple_iter.next().is_some() {+ state+ .warnings+ .register_warning(PydanticSerializationUnexpectedValue::new_from_msg(Some(+ "Unexpected extra items present in named tuple".to_string(),+ )));+ }++ Ok(Ok(()))+ }+}pydantic-core/src/validators/mod.rsindex 7a6875e3d..326ef5cd3 100644@@ -55,6 +55,7 @@ mod literal; mod missing_sentinel; mod model; mod model_fields;+mod named_tuple; mod none; mod nullable; mod prebuilt;@@ -578,6 +579,8 @@ fn build_validator_inner( // dataclasses dataclass::DataclassArgsValidator, dataclass::DataclassValidator,+ // named tuples+ named_tuple::NamedTupleValidator, // strings string::StrValidator, // integers@@ -742,6 +745,8 @@ pub enum CombinedValidator { // dataclasses DataclassArgs(dataclass::DataclassArgsValidator), Dataclass(dataclass::DataclassValidator),+ // named tuples+ NamedTuple(named_tuple::NamedTupleValidator), // strings Str(string::StrValidator), StrConstrained(string::StrConstrainedValidator),pydantic-core/src/validators/named_tuple.rsnew file mode 100644index 000000000..ae944092a@@ -0,0 +1,385 @@+use std::sync::Arc;++use pyo3::intern;+use pyo3::prelude::*;+use pyo3::pybacked::PyBackedStr;+use pyo3::types::{PyDict, PyList, PyTuple, PyType};++use ahash::AHashSet;++use crate::build_tools::py_schema_err;+use crate::errors::{ErrorType, ErrorTypeDefaults, LocItem, ValError, ValLineError, ValResult, py_err_string};+use crate::input::{+ BorrowInput, ConsumeIterator, Input, ValidatedDict, ValidatedTuple, ValidationMatch, input_as_python_instance,+};+use crate::lookup_key::{LookupPathCollection, LookupType};+use crate::tools::SchemaDict;+use crate::validators::function::convert_err;++use super::validation_state::Exactness;+use super::{BuildValidator, CombinedValidator, DefinitionsBuilder, ValidationState, Validator, build_validator};++#[derive(Debug)]+struct NamedTupleField {+ name: PyBackedStr,+ lookup_path_collection: LookupPathCollection,+ validator: Arc<CombinedValidator>,+}++impl_py_gc_traverse!(NamedTupleField { validator });++#[derive(Debug)]+pub struct NamedTupleValidator {+ class: Py<PyType>,+ fields: Vec<NamedTupleField>,+ loc_by_alias: bool,+ validate_by_alias: Option<bool>,+ validate_by_name: Option<bool>,+ name: String,+}++impl BuildValidator for NamedTupleValidator {+ const EXPECTED_TYPE: &'static str = "named-tuple";++ fn build(+ schema: &Bound<'_, PyDict>,+ config: Option<&Bound<'_, PyDict>>,+ definitions: &mut DefinitionsBuilder<Arc<CombinedValidator>>,+ ) -> PyResult<Arc<CombinedValidator>> {+ let py = schema.py();++ let class = schema.get_as_req::<Bound<'_, PyType>>(intern!(py, "cls"))?;+ let name = match schema.get_as::<String>(intern!(py, "cls_name"))? {+ Some(name) => name,+ None => class.getattr(intern!(py, "__name__"))?.extract()?,+ };++ let fields_list: Bound<'_, PyList> = schema.get_as_req(intern!(py, "fields"))?;+ let mut fields: Vec<NamedTupleField> = Vec::with_capacity(fields_list.len());++ for field in fields_list {+ let field = field.cast::<PyDict>()?;++ let field_name: PyBackedStr = field.get_as_req(intern!(py, "name"))?;++ let schema = field.get_as_req(intern!(py, "schema"))?;+ let validator = match build_validator(&schema, config, definitions) {+ Ok(v) => v,+ Err(err) => return py_schema_err!("Field '{field_name}':\n {err}"),+ };++ if let CombinedValidator::WithDefault(v) = validator.as_ref()+ && v.omit_on_error()+ {+ return py_schema_err!("Field '{field_name}': 'on_error = omit' cannot be set for named tuple fields");+ }++ let validation_alias = field.get_as(intern!(py, "validation_alias"))?;+ let lookup_path_collection = LookupPathCollection::new(validation_alias, field_name.clone())?;++ fields.push(NamedTupleField {+ name: field_name,+ lookup_path_collection,+ validator,+ });+ }++ Ok(CombinedValidator::NamedTuple(Self {+ class: class.into(),+ fields,+ loc_by_alias: config.get_as(intern!(py, "loc_by_alias"))?.unwrap_or(true),+ validate_by_alias: config.get_as(intern!(py, "validate_by_alias"))?,+ validate_by_name: config.get_as(intern!(py, "validate_by_name"))?,+ name,+ })+ .into())+ }+}++impl_py_gc_traverse!(NamedTupleValidator { class, fields });++impl Validator for NamedTupleValidator {+ fn validate<'py>(+ &self,+ py: Python<'py>,+ input: &(impl Input<'py> + ?Sized),+ state: &mut ValidationState<'_, 'py>,+ ) -> ValResult<Py<PyAny>> {+ // this validator does not yet support partial validation, disable it to avoid incorrect results+ state.allow_partial = false.into();++ let class = self.class.bind(py);++ if let Some(py_input) = input_as_python_instance(input, class) {+ // An instance of the named tuple class itself; revalidate the items (using+ // field names in error locations) and reconstruct an instance. Exactness is+ // left untouched, so that the nominal class is preserved in smart unions:+ let collection = py_input.validate_tuple(false)?.unpack(state);+ let items = self.validate_tuple_collection(py, input, state, collection, true)?;+ return self.create_instance(py, input, items);+ }++ // Note: strict mode is currently ignored, as the `'call'` core schema previously+ // used for named tuples had no strict behavior:+ match input.validate_tuple(false) {+ Ok(tuple_match) => {+ // A tuple, list or JSON array; validate positionally, using indices in error locations:+ let collection = tuple_match.unpack(state);+ let items = self.validate_tuple_collection(py, input, state, collection, false)?;+ state.floor_exactness(Exactness::Strict);+ self.create_instance(py, input, items)+ }+ Err(ValError::LineErrors(_)) => match input.validate_dict(false) {+ Ok(dict) => {+ // A dict, mapping or JSON object; validate by field name:+ let items = self.validate_dict_input(py, input, state, &dict)?;+ state.floor_exactness(Exactness::Strict);+ self.create_instance(py, input, items)+ }+ Err(ValError::LineErrors(_)) => Err(ValError::new(+ ErrorType::NamedTupleType {+ class_name: self.name.clone(),+ context: None,+ },+ input,+ )),+ Err(err) => Err(err),+ },+ Err(err) => Err(err),+ }+ }++ fn get_name(&self) -> &str {+ &self.name+ }+}++impl NamedTupleValidator {+ fn validate_tuple_collection<'py, T: ValidatedTuple<'py>>(+ &self,+ py: Python<'py>,+ input: &(impl Input<'py> + ?Sized),+ state: &mut ValidationState<'_, 'py>,+ collection: T,+ name_locs: bool,+ ) -> ValResult<Vec<Py<PyAny>>> {+ let actual_length = collection.len();++ collection.iterate(ValidateItems {+ py,+ input,+ actual_length,+ validator: self,+ state,+ name_locs,+ })?+ }++ fn validate_dict_input<'py>(+ &self,+ py: Python<'py>,+ input: &(impl Input<'py> + ?Sized),+ state: &mut ValidationState<'_, 'py>,+ dict: &impl ValidatedDict<'py>,+ ) -> ValResult<Vec<Py<PyAny>>> {+ let mut output: Vec<Py<PyAny>> = Vec::with_capacity(self.fields.len());+ let mut errors: Vec<ValLineError> = Vec::new();+ let mut used_keys: AHashSet<&str> = AHashSet::with_capacity(self.fields.len());++ let validate_by_alias = state.validate_by_alias_or(self.validate_by_alias);+ let validate_by_name = state.validate_by_name_or(self.validate_by_name);+ let lookup_type = LookupType::from_bools(validate_by_alias, validate_by_name)?;++ for field in &self.fields {+ if let Some((lookup_path, lookup_result)) = field+ .lookup_path_collection+ .lookup_paths(lookup_type)+ .find_map(|path| Some((path, dict.get_item(path).transpose()?)))+ {+ let value = lookup_result?;+ used_keys.insert(lookup_path.first_key());++ let state = &mut state.scoped_set_field_name(Some(field.name.as_py_str().bind(py).clone()));++ match field.validator.validate(py, value.borrow_input(), state) {+ Ok(value) => output.push(value),+ Err(ValError::LineErrors(line_errors)) => {+ errors.extend(+ line_errors+ .into_iter()+ .map(|err| lookup_path.apply_error_loc(err, self.loc_by_alias, &field.name)),+ );+ }+ Err(err) => return Err(err),+ }+ continue;+ }++ match field.validator.default_value(py, Some(field.name.clone()), state) {+ Ok(Some(value)) => output.push(value),+ Ok(None) => {+ let error_loc = field.lookup_path_collection.error_loc(lookup_type, self.loc_by_alias);+ errors.push(ValLineError::new_with_full_loc(+ ErrorTypeDefaults::Missing,+ input,+ error_loc,+ ));+ }+ Err(ValError::LineErrors(line_errors)) => {+ // Note: this will always use the field name even if there is an alias+ // However, we don't mind so much because this error can only happen if the+ // default value fails validation, which is arguably a developer error.+ errors.extend(line_errors);+ }+ Err(err) => return Err(err),+ }+ }++ dict.iterate(CheckExtras {+ used_keys,+ errors: &mut errors,+ })??;++ if errors.is_empty() {+ Ok(output)+ } else {+ Err(ValError::LineErrors(errors))+ }+ }++ fn create_instance<'py>(+ &self,+ py: Python<'py>,+ input: &(impl Input<'py> + ?Sized),+ items: Vec<Py<PyAny>>,+ ) -> ValResult<Py<PyAny>> {+ let args = PyTuple::new(py, items)?;+ match self.class.bind(py).call1(args) {+ Ok(instance) => Ok(instance.unbind()),+ Err(e) => Err(convert_err(py, e, input)),+ }+ }+}++struct CheckExtras<'a> {+ used_keys: AHashSet<&'a str>,+ errors: &'a mut Vec<ValLineError>,+}++impl<'py, Key, Value> ConsumeIterator<ValResult<(Key, Value)>> for CheckExtras<'_>+where+ Key: BorrowInput<'py> + Clone + Into<LocItem>,+ Value: BorrowInput<'py>,+{+ type Output = ValResult<()>;+ fn consume_iterator(self, iterator: impl Iterator<Item = ValResult<(Key, Value)>>) -> ValResult<()> {+ for item_result in iterator {+ let (raw_key, value) = item_result?;+ let either_str = match raw_key+ .borrow_input()+ .validate_str(true, false)+ .map(ValidationMatch::into_inner)+ {+ Ok(k) => k,+ Err(ValError::LineErrors(line_errors)) => {+ for err in line_errors {+ self.errors.push(+ err.with_outer_location(raw_key.clone())+ .with_type(ErrorTypeDefaults::InvalidKey),+ );+ }+ continue;+ }+ Err(err) => return Err(err),+ };+ if !self.used_keys.contains(either_str.as_cow()?.as_ref()) {+ // Named tuples cannot hold extra fields, so extra keys are always forbidden:+ self.errors.push(ValLineError::new_with_loc(+ ErrorTypeDefaults::ExtraForbidden,+ value.borrow_input(),+ raw_key.clone(),+ ));+ }+ }+ Ok(())+ }+}++struct ValidateItems<'a, 's, 'py, I: Input<'py> + ?Sized> {+ py: Python<'py>,+ input: &'a I,+ actual_length: Option<usize>,+ validator: &'a NamedTupleValidator,+ state: &'a mut ValidationState<'s, 'py>,+ name_locs: bool,+}++impl<'py, T, I> ConsumeIterator<PyResult<T>> for ValidateItems<'_, '_, 'py, I>+where+ T: BorrowInput<'py>,+ I: Input<'py> + ?Sized,+{+ type Output = ValResult<Vec<Py<PyAny>>>;+ fn consume_iterator(self, mut iterator: impl Iterator<Item = PyResult<T>>) -> ValResult<Vec<Py<PyAny>>> {+ let fields = &self.validator.fields;+ let mut output: Vec<Py<PyAny>> = Vec::with_capacity(fields.len());+ let mut errors: Vec<ValLineError> = Vec::new();++ for (index, field) in fields.iter().enumerate() {+ let loc: LocItem = if self.name_locs {+ field.name.clone().into()+ } else {+ index.into()+ };+ match iterator.next() {+ Some(Ok(item)) => {+ let state = &mut self+ .state+ .scoped_set_field_name(Some(field.name.as_py_str().bind(self.py).clone()));+ match field.validator.validate(self.py, item.borrow_input(), state) {+ Ok(value) => output.push(value),+ Err(ValError::LineErrors(line_errors)) => {+ errors.extend(line_errors.into_iter().map(|err| err.with_outer_location(loc.clone())));+ }+ Err(err) => return Err(err),+ }+ }+ Some(Err(e)) => {+ return Err(ValError::new_with_loc(+ ErrorType::IterationError {+ error: py_err_string(self.py, e),+ context: None,+ },+ self.input,+ index,+ ));+ }+ None => match field.validator.default_value(self.py, Some(loc.clone()), self.state)? {+ Some(value) => output.push(value),+ None => {+ errors.push(ValLineError::new_with_loc(ErrorTypeDefaults::Missing, self.input, loc));+ }+ },+ }+ }++ // Generate an error if there are any extra items:+ if iterator.next().is_some() {+ return Err(ValError::new(+ ErrorType::TooLong {+ field_type: "NamedTuple".to_string(),+ max_length: fields.len(),+ actual_length: self.actual_length,+ context: None,+ },+ self.input,+ ));+ }++ if errors.is_empty() {+ Ok(output)+ } else {+ Err(ValError::LineErrors(errors))+ }+ }+}pydantic-core/tests/test_errors.pyindex 334e281bd..00b6d263e 100644@@ -267,6 +267,11 @@ all_errors = [ ('model_attributes_type', 'Input should be a valid dictionary or object to extract fields from', None), ('dataclass_exact_type', 'Input should be an instance of Foobar', {'class_name': 'Foobar'}), ('dataclass_type', 'Input should be a dictionary or an instance of Foobar', {'class_name': 'Foobar'}),+ (+ 'named_tuple_type',+ 'Input should be a tuple, list, dictionary or an instance of Foobar',+ {'class_name': 'Foobar'},+ ), ( 'default_factory_not_called', 'The default factory uses validated data, but at least one validation error occurred',pydantic-core/tests/test_schema_functions.pyindex 65a015a6f..8bb07dfb8 100644@@ -1,7 +1,7 @@ import dataclasses from datetime import date from enum import Enum-from typing import Any+from typing import Any, NamedTuple import pytest from typing_extensions import get_args, get_type_hints # noqa: UP035@@ -28,6 +28,10 @@ class MyDataclass: y: str +class MyNamedTuple(NamedTuple):+ foo: int++ class MyEnum(int, Enum): a = 1 b = 2@@ -308,6 +312,15 @@ all_schema_functions = [ args(MyDataclass, {'type': 'int'}, ['foobar'], slots=True), {'type': 'dataclass', 'schema': {'type': 'int'}, 'fields': ['foobar'], 'cls': MyDataclass, 'slots': True}, ),+ (+ core_schema.named_tuple_schema,+ args(MyNamedTuple, [{'name': 'foo', 'type': 'named-tuple-field', 'schema': {'type': 'int'}}]),+ {+ 'type': 'named-tuple',+ 'cls': MyNamedTuple,+ 'fields': [{'name': 'foo', 'type': 'named-tuple-field', 'schema': {'type': 'int'}}],+ },+ ), (core_schema.uuid_schema, args(), {'type': 'uuid'}), (core_schema.decimal_schema, args(), {'type': 'decimal'}), (core_schema.decimal_schema, args(multiple_of=5, gt=1.2), {'type': 'decimal', 'multiple_of': 5, 'gt': 1.2}),pydantic/_internal/_generate_schema.pyindex d52930dc0..53971d205 100644@@ -1555,21 +1555,56 @@ class GenerateSchema: for field_name, annotation in annotations.items() } - arguments_schema = core_schema.arguments_schema(+ schema = core_schema.named_tuple_schema(+ namedtuple_cls, [- self._generate_parameter_schema(+ self._generate_namedtuple_field_schema( field_name, annotation,- source=AnnotationSource.NAMED_TUPLE, default=namedtuple_cls._field_defaults.get(field_name, Parameter.empty), ) for field_name, annotation in annotations.items() ],- metadata={'pydantic_js_prefer_positional_arguments': True},+ ref=namedtuple_ref, )- schema = core_schema.call_schema(arguments_schema, namedtuple_cls, ref=namedtuple_ref) return self.defs.create_definition_reference_schema(schema) + def _generate_namedtuple_field_schema(+ self,+ name: str,+ annotation: Any,+ default: Any = Parameter.empty,+ ) -> core_schema.NamedTupleField:+ """Generate the definition of a field in a named tuple."""+ FieldInfo = import_cached_field_info()++ if default is Parameter.empty:+ field = FieldInfo.from_annotation(annotation, _source=AnnotationSource.NAMED_TUPLE)+ else:+ field = FieldInfo.from_annotated_attribute(annotation, default, _source=AnnotationSource.NAMED_TUPLE)++ assert field.annotation is not None, 'field.annotation should not be None when generating a schema'+ update_field_from_config(self._config_wrapper, name, field)++ with self.field_name_stack.push(name):+ schema = self._apply_annotations(+ field.annotation,+ [field],+ # Because we pass `field` as metadata above (required for attributes relevant for+ # JSON Scheme generation), we need to ignore the potential warnings about `FieldInfo`+ # attributes that will not be used:+ check_unsupported_field_info_attributes=False,+ )++ if not field.is_required():+ schema = wrap_default(field, schema)++ return core_schema.named_tuple_field(+ name,+ schema,+ validation_alias=_convert_to_aliases(field.validation_alias),+ )+ def _generate_parameter_schema( self, name: str,@@ -1578,7 +1613,7 @@ class GenerateSchema: default: Any = Parameter.empty, mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None, ) -> core_schema.ArgumentsParameter:- """Generate the definition of a field in a namedtuple or a parameter in a function signature.+ """Generate the definition of a parameter in a function signature. This definition is meant to be used for the `'arguments'` core schema, which will be replaced in V3 by the `'arguments-v3`'.pydantic/_internal/_schema_gather.pyindex 0e35d9915..f176629c8 100644@@ -185,6 +185,9 @@ def traverse_schema(schema: AllSchemas, context: GatherContext) -> None: traverse_schema(s, context) for s in schema['fields']: traverse_schema(s, context)+ elif schema_type == 'named-tuple':+ for s in schema['fields']:+ traverse_schema(s, context) elif schema_type == 'arguments': for s in schema['arguments_schema']: traverse_schema(s['schema'], context)pydantic/json_schema.pyindex c6adb6947..f6da6fc34 100644@@ -1875,6 +1875,55 @@ class GenerateJsonSchema: return json_schema + def named_tuple_field_schema(self, schema: core_schema.NamedTupleField) -> JsonSchemaValue:+ """Generates a JSON schema that matches a schema that defines a named tuple field.++ Args:+ schema: The core schema.++ Returns:+ The generated JSON schema.+ """+ return self.generate_inner(schema['schema'])++ def named_tuple_schema(self, schema: core_schema.NamedTupleSchema) -> JsonSchemaValue:+ """Generates a JSON schema that matches a schema that defines a named tuple.++ Args:+ schema: The core schema.++ Returns:+ The generated JSON schema.+ """+ prefix_items: list[JsonSchemaValue] = []+ min_items = 0++ for field in schema['fields']:+ name = field['name']+ if self.by_alias:+ alias = field.get('validation_alias')+ if isinstance(alias, str):+ name = alias++ field_schema = self.generate_inner(field['schema']).copy()+ if 'title' not in field_schema and self.field_title_should_be_set(field['schema']):+ field_schema['title'] = self.get_title_from_name(name)+ prefix_items.append(field_schema)++ if field['schema']['type'] != 'default':+ # This assumes that if the field has a default value,+ # the inner schema must be of type WithDefaultSchema.+ min_items += 1++ json_schema: JsonSchemaValue = {'type': 'array'}+ if prefix_items:+ json_schema['prefixItems'] = prefix_items+ if min_items:+ json_schema['minItems'] = min_items+ json_schema['maxItems'] = len(prefix_items)++ return json_schema+ def arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue: """Generates a JSON schema that matches a schema that defines a function's arguments. tests/test_json_schema.pyindex 633abea77..077116ffa 100644@@ -3533,7 +3533,8 @@ def test_namedtuple_modify_schema(): @classmethod def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: schema = handler(source)- schema['arguments_schema']['metadata']['pydantic_js_prefer_positional_arguments'] = False+ assert schema['type'] == 'named-tuple'+ schema['fields'][0]['schema'] = core_schema.int_schema() return schema class Location(BaseModel):@@ -3542,13 +3543,13 @@ def test_namedtuple_modify_schema(): assert Location.model_json_schema() == { '$defs': { 'CustomCoordinates': {- 'additionalProperties': False,- 'properties': {'x': {'title': 'X', 'type': 'number'}, 'y': {'title': 'Y', 'type': 'number'}},- 'required': ['x', 'y'],- 'type': 'object',+ 'maxItems': 2,+ 'minItems': 2,+ 'prefixItems': [{'title': 'X', 'type': 'integer'}, {'title': 'Y', 'type': 'number'}],+ 'type': 'array', } },- 'properties': {'coords': {'$ref': '#/$defs/CustomCoordinates', 'default': [34, 42]}},+ 'properties': {'coords': {'$ref': '#/$defs/CustomCoordinates', 'default': [34, 42.0]}}, 'title': 'Location', 'type': 'object', }tests/test_types_namedtuple.pydeleted file mode 100644index 7c72db4d4..000000000@@ -1,256 +0,0 @@-from collections import namedtuple-from typing import Generic, NamedTuple, Optional, TypeVar--import pytest-from typing_extensions import NamedTuple as TypingExtensionsNamedTuple--from pydantic import BaseModel, ConfigDict, PositiveInt, TypeAdapter, ValidationError-from pydantic.errors import PydanticSchemaGenerationError---def test_namedtuple_simple():- Position = namedtuple('Pos', 'x y')-- class Model(BaseModel):- pos: Position-- model = Model(pos=('1', 2))- assert isinstance(model.pos, Position)- assert model.pos.x == '1'- assert model.pos == Position('1', 2)-- model = Model(pos={'x': '1', 'y': 2})- assert model.pos == Position('1', 2)---def test_namedtuple():- class Event(NamedTuple):- a: int- b: int- c: int- d: str-- class Model(BaseModel):- # pos: Position- event: Event-- model = Model(event=(b'1', '2', 3, 'qwe'))- assert isinstance(model.event, Event)- assert model.event == Event(1, 2, 3, 'qwe')- assert repr(model) == "Model(event=Event(a=1, b=2, c=3, d='qwe'))"-- with pytest.raises(ValidationError) as exc_info:- Model(pos=('1', 2), event=['qwe', '2', 3, 'qwe'])- # insert_assert(exc_info.value.errors(include_url=False))- assert exc_info.value.errors(include_url=False) == [- {- 'type': 'int_parsing',- 'loc': ('event', 0),- 'msg': 'Input should be a valid integer, unable to parse string as an integer',- 'input': 'qwe',- }- ]---def test_namedtuple_schema():- class Position1(NamedTuple):- x: int- y: int-- Position2 = namedtuple('Position2', 'x y')-- class Model(BaseModel):- pos1: Position1- pos2: Position2- pos3: tuple[int, int]-- assert Model.model_json_schema() == {- 'title': 'Model',- 'type': 'object',- '$defs': {- 'Position1': {- 'maxItems': 2,- 'minItems': 2,- 'prefixItems': [{'title': 'X', 'type': 'integer'}, {'title': 'Y', 'type': 'integer'}],- 'type': 'array',- },- 'Position2': {- 'maxItems': 2,- 'minItems': 2,- 'prefixItems': [{'title': 'X'}, {'title': 'Y'}],- 'type': 'array',- },- },- 'properties': {- 'pos1': {'$ref': '#/$defs/Position1'},- 'pos2': {'$ref': '#/$defs/Position2'},- 'pos3': {- 'maxItems': 2,- 'minItems': 2,- 'prefixItems': [{'type': 'integer'}, {'type': 'integer'}],- 'title': 'Pos3',- 'type': 'array',- },- },- 'required': ['pos1', 'pos2', 'pos3'],- }---def test_namedtuple_right_length():- class Point(NamedTuple):- x: int- y: int-- class Model(BaseModel):- p: Point-- assert isinstance(Model(p=(1, 2)), Model)-- with pytest.raises(ValidationError) as exc_info:- Model(p=(1, 2, 3))- # insert_assert(exc_info.value.errors(include_url=False))- assert exc_info.value.errors(include_url=False) == [- {- 'type': 'unexpected_positional_argument',- 'loc': ('p', 2),- 'msg': 'Unexpected positional argument',- 'input': 3,- }- ]---def test_namedtuple_postponed_annotation():- """- https://github.com/pydantic/pydantic/issues/2760- """-- class Tup(NamedTuple):- v: 'PositiveInt'-- class Model(BaseModel):- t: Tup-- # The effect of issue #2760 is that this call raises a `PydanticUserError` even though the type declared on `Tup.v`- # references a binding in this module's global scope.- with pytest.raises(ValidationError):- Model.model_validate({'t': [-1]})---def test_namedtuple_different_module(create_module) -> None:- """https://github.com/pydantic/pydantic/issues/10336"""-- @create_module- def other_module():- from typing import NamedTuple-- TestIntOtherModule = int-- class Tup(NamedTuple):- f: 'TestIntOtherModule'-- class Model(BaseModel):- tup: other_module.Tup-- assert Model(tup={'f': 1}).tup.f == 1---def test_namedtuple_arbitrary_type():- class CustomClass:- pass-- class Tup(NamedTuple):- c: CustomClass-- class Model(BaseModel):- x: Tup-- model_config = ConfigDict(arbitrary_types_allowed=True)-- data = {'x': Tup(c=CustomClass())}- model = Model.model_validate(data)- assert isinstance(model.x.c, CustomClass)-- with pytest.raises(PydanticSchemaGenerationError):-- class ModelNoArbitraryTypes(BaseModel):- x: Tup---def test_recursive_namedtuple():- class MyNamedTuple(NamedTuple):- x: int- y: Optional['MyNamedTuple']-- ta = TypeAdapter(MyNamedTuple)- assert ta.validate_python({'x': 1, 'y': {'x': 2, 'y': None}}) == (1, (2, None))-- with pytest.raises(ValidationError) as exc_info:- ta.validate_python({'x': 1, 'y': {'x': 2, 'y': {'x': 'a', 'y': None}}})- assert exc_info.value.errors(include_url=False) == [- {- 'input': 'a',- 'loc': ('y', 'y', 'x'),- 'msg': 'Input should be a valid integer, unable to parse string as an integer',- 'type': 'int_parsing',- }- ]---def test_recursive_generic_namedtuple():- # Need to use TypingExtensionsNamedTuple to make it work with Python <3.11- T = TypeVar('T')-- class MyNamedTuple(TypingExtensionsNamedTuple, Generic[T]):- x: T- y: Optional['MyNamedTuple[T]']-- ta = TypeAdapter(MyNamedTuple[int])- assert ta.validate_python({'x': 1, 'y': {'x': 2, 'y': None}}) == (1, (2, None))-- with pytest.raises(ValidationError) as exc_info:- ta.validate_python({'x': 1, 'y': {'x': 2, 'y': {'x': 'a', 'y': None}}})- assert exc_info.value.errors(include_url=False) == [- {- 'input': 'a',- 'loc': ('y', 'y', 'x'),- 'msg': 'Input should be a valid integer, unable to parse string as an integer',- 'type': 'int_parsing',- }- ]---def test_namedtuple_defaults():- class NT(NamedTuple):- x: int- y: int = 33-- assert TypeAdapter(NT).validate_python([1]) == (1, 33)- assert TypeAdapter(NT).validate_python({'x': 22}) == (22, 33)---def test_namedtuple_inheritance_with_annotations():- """https://github.com/pydantic/pydantic/issues/7987."""-- class Foo(NamedTuple):- test: str- test2: str-- class Bar(Foo):- test3: str-- ta = TypeAdapter(Bar)-- # test3 should not be part of the schema- assert ta.validate_python({'test': 'a', 'test2': 'b'}) == Bar(test='a', test2='b')-- with pytest.raises(ValidationError) as exc_info:- ta.validate_python({'test': 'a', 'test2': 'b', 'test3': 'c'})-- assert exc_info.value.errors(include_url=False) == [- {- 'type': 'unexpected_keyword_argument',- 'loc': ('test3',),- 'msg': 'Unexpected keyword argument',- 'input': 'c',- }- ]tests/types/test_namedtuple.pynew file mode 100644index 000000000..8660e0912@@ -0,0 +1,535 @@+from collections import namedtuple+from collections.abc import Mapping+from typing import Annotated, Generic, NamedTuple, Optional, TypeVar++import pytest+from typing_extensions import NamedTuple as TypingExtensionsNamedTuple++from pydantic import BaseModel, ConfigDict, Field, PlainSerializer, PositiveInt, TypeAdapter, ValidationError+from pydantic.errors import PydanticSchemaGenerationError+++def test_namedtuple_simple():+ Position = namedtuple('Pos', 'x y')++ class Model(BaseModel):+ pos: Position++ model = Model(pos=('1', 2))+ assert isinstance(model.pos, Position)+ assert model.pos.x == '1'+ assert model.pos == Position('1', 2)++ model = Model(pos={'x': '1', 'y': 2})+ assert model.pos == Position('1', 2)+++def test_namedtuple():+ class Event(NamedTuple):+ a: int+ b: int+ c: int+ d: str++ class Model(BaseModel):+ event: Event++ model = Model(event=(b'1', '2', 3, 'qwe'))+ assert isinstance(model.event, Event)+ assert model.event == Event(1, 2, 3, 'qwe')+ assert repr(model) == "Model(event=Event(a=1, b=2, c=3, d='qwe'))"++ with pytest.raises(ValidationError) as exc_info:+ Model(pos=('1', 2), event=['qwe', '2', 3, 'qwe'])+ # insert_assert(exc_info.value.errors(include_url=False))+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'int_parsing',+ 'loc': ('event', 0),+ 'msg': 'Input should be a valid integer, unable to parse string as an integer',+ 'input': 'qwe',+ }+ ]+++def test_namedtuple_schema():+ class Position1(NamedTuple):+ x: int+ y: int++ Position2 = namedtuple('Position2', 'x y')++ class Model(BaseModel):+ pos1: Position1+ pos2: Position2+ pos3: tuple[int, int]++ assert Model.model_json_schema() == {+ 'title': 'Model',+ 'type': 'object',+ '$defs': {+ 'Position1': {+ 'maxItems': 2,+ 'minItems': 2,+ 'prefixItems': [{'title': 'X', 'type': 'integer'}, {'title': 'Y', 'type': 'integer'}],+ 'type': 'array',+ },+ 'Position2': {+ 'maxItems': 2,+ 'minItems': 2,+ 'prefixItems': [{'title': 'X'}, {'title': 'Y'}],+ 'type': 'array',+ },+ },+ 'properties': {+ 'pos1': {'$ref': '#/$defs/Position1'},+ 'pos2': {'$ref': '#/$defs/Position2'},+ 'pos3': {+ 'maxItems': 2,+ 'minItems': 2,+ 'prefixItems': [{'type': 'integer'}, {'type': 'integer'}],+ 'title': 'Pos3',+ 'type': 'array',+ },+ },+ 'required': ['pos1', 'pos2', 'pos3'],+ }+++def test_namedtuple_right_length():+ class Point(NamedTuple):+ x: int+ y: int++ class Model(BaseModel):+ p: Point++ assert isinstance(Model(p=(1, 2)), Model)++ with pytest.raises(ValidationError) as exc_info:+ Model(p=(1, 2, 3))+ # insert_assert(exc_info.value.errors(include_url=False))+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'too_long',+ 'loc': ('p',),+ 'msg': 'NamedTuple should have at most 2 items after validation, not 3',+ 'input': (1, 2, 3),+ 'ctx': {'field_type': 'NamedTuple', 'max_length': 2, 'actual_length': 3},+ }+ ]+++def test_namedtuple_postponed_annotation():+ """https://github.com/pydantic/pydantic/issues/2760"""++ class Tup(NamedTuple):+ v: 'PositiveInt'++ class Model(BaseModel):+ t: Tup++ # The effect of issue #2760 is that this call raises a `PydanticUserError` even though the type declared on `Tup.v`+ # references a binding in this module's global scope.+ with pytest.raises(ValidationError):+ Model.model_validate({'t': [-1]})+++def test_namedtuple_different_module(create_module) -> None:+ """https://github.com/pydantic/pydantic/issues/10336"""++ @create_module+ def other_module():+ from typing import NamedTuple++ TestIntOtherModule = int++ class Tup(NamedTuple):+ f: 'TestIntOtherModule'++ class Model(BaseModel):+ tup: other_module.Tup++ assert Model(tup={'f': 1}).tup.f == 1+++def test_namedtuple_arbitrary_type():+ class CustomClass:+ pass++ class Tup(NamedTuple):+ c: CustomClass++ class Model(BaseModel):+ x: Tup++ model_config = ConfigDict(arbitrary_types_allowed=True)++ data = {'x': Tup(c=CustomClass())}+ model = Model.model_validate(data)+ assert isinstance(model.x.c, CustomClass)++ with pytest.raises(PydanticSchemaGenerationError):++ class ModelNoArbitraryTypes(BaseModel):+ x: Tup+++def test_recursive_namedtuple():+ class MyNamedTuple(NamedTuple):+ x: int+ y: Optional['MyNamedTuple']++ ta = TypeAdapter(MyNamedTuple)+ assert ta.validate_python({'x': 1, 'y': {'x': 2, 'y': None}}) == (1, (2, None))++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python({'x': 1, 'y': {'x': 2, 'y': {'x': 'a', 'y': None}}})+ assert exc_info.value.errors(include_url=False) == [+ {+ 'input': 'a',+ 'loc': ('y', 'y', 'x'),+ 'msg': 'Input should be a valid integer, unable to parse string as an integer',+ 'type': 'int_parsing',+ }+ ]+++def test_recursive_generic_namedtuple():+ # Need to use TypingExtensionsNamedTuple to make it work with Python <3.11+ T = TypeVar('T')++ class MyNamedTuple(TypingExtensionsNamedTuple, Generic[T]):+ x: T+ y: Optional['MyNamedTuple[T]']++ ta = TypeAdapter(MyNamedTuple[int])+ assert ta.validate_python({'x': 1, 'y': {'x': 2, 'y': None}}) == (1, (2, None))++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python({'x': 1, 'y': {'x': 2, 'y': {'x': 'a', 'y': None}}})+ assert exc_info.value.errors(include_url=False) == [+ {+ 'input': 'a',+ 'loc': ('y', 'y', 'x'),+ 'msg': 'Input should be a valid integer, unable to parse string as an integer',+ 'type': 'int_parsing',+ }+ ]+++def test_namedtuple_defaults():+ class NT(NamedTuple):+ x: int+ y: int = 33++ assert TypeAdapter(NT).validate_python([1]) == (1, 33)+ assert TypeAdapter(NT).validate_python({'x': 22}) == (22, 33)+++def test_namedtuple_inheritance_with_annotations():+ """https://github.com/pydantic/pydantic/issues/7987."""++ class Foo(NamedTuple):+ test: str+ test2: str++ class Bar(Foo):+ test3: str++ ta = TypeAdapter(Bar)++ # test3 should not be part of the schema+ assert ta.validate_python({'test': 'a', 'test2': 'b'}) == Bar(test='a', test2='b')++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python({'test': 'a', 'test2': 'b', 'test3': 'c'})++ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'extra_forbidden',+ 'loc': ('test3',),+ 'msg': 'Extra inputs are not permitted',+ 'input': 'c',+ }+ ]+++def test_namedtuple_smart_union_preserves_class():+ """https://github.com/pydantic/pydantic/issues/12529"""++ class A(NamedTuple):+ x: int++ class B(NamedTuple):+ x: int++ class Model(BaseModel):+ a_or_b: A | B++ assert type(Model(a_or_b=B(x=1)).a_or_b) is B+ assert type(Model(a_or_b=A(x=1)).a_or_b) is A+ # Non-instance inputs still use the first matching member:+ assert type(Model(a_or_b=(1,)).a_or_b) is A+++def test_namedtuple_field_serializers():+ """https://github.com/pydantic/pydantic/issues/8155"""++ from pydantic import PlainSerializer++ HexInt = Annotated[int, PlainSerializer(hex, return_type=str)]++ class NT(NamedTuple):+ x: HexInt++ ta = TypeAdapter(NT)+ assert ta.dump_python(NT(255)) == ('0xff',)+ assert ta.dump_json(NT(255)) == b'["0xff"]'+++def test_namedtuple_defer_build_serialization():+ """https://github.com/pydantic/pydantic/issues/13448"""++ class LazyModel(BaseModel, defer_build=True):+ x: int++ class LazyNT(NamedTuple):+ bar: LazyModel++ class Model(BaseModel):+ nt: LazyNT++ m = Model(nt=[{'x': 1}])+ assert m.model_dump() == {'nt': ({'x': 1},)}+ assert m.model_dump_json() == '{"nt":[{"x":1}]}'+++def test_namedtuple_from_attributes_error_locs():+ """https://github.com/pydantic/pydantic/issues/11925++ Field names (not indices) are used in error locations when validating+ an instance of the named tuple class.+ """++ class NT(NamedTuple):+ x: Annotated[int, Field(gt=0)]++ class Model(BaseModel):+ nt: NT++ class Attributes:+ def __init__(self):+ self.nt = NT(x=0)++ with pytest.raises(ValidationError) as exc_info:+ Model.model_validate(Attributes(), from_attributes=True)+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'greater_than',+ 'loc': ('nt', 'x'),+ 'msg': 'Input should be greater than 0',+ 'input': 0,+ 'ctx': {'gt': 0},+ }+ ]+++def test_namedtuple_strict_ignored():+ """Strict mode is currently ignored for named tuples, matching the behavior of the+ `'call'` core schema previously used for them."""++ class NT(NamedTuple):+ x: int++ ta = TypeAdapter(NT)++ assert ta.validate_python(NT(1), strict=True) == NT(1)+ assert ta.validate_python((1,), strict=True) == NT(1)+ assert ta.validate_python([1], strict=True) == NT(1)+ assert ta.validate_python({'x': 1}, strict=True) == NT(1)+ assert ta.validate_json('[1]', strict=True) == NT(1)+ assert ta.validate_json('{"x": 1}', strict=True) == NT(1)+++def test_namedtuple_instances_revalidated():+ class NT(NamedTuple):+ x: int++ ta = TypeAdapter(NT)+ validated = ta.validate_python(NT(x='1'))+ assert validated.x == 1+++def test_namedtuple_invalid_input_type():+ class Point(NamedTuple):+ x: int+ y: int++ ta = TypeAdapter(Point)++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python('invalid')+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'named_tuple_type',+ 'loc': (),+ 'msg': 'Input should be a tuple, list, dictionary or an instance of Point',+ 'input': 'invalid',+ 'ctx': {'class_name': 'Point'},+ }+ ]++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_json('"invalid"')+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'named_tuple_type',+ 'loc': (),+ 'msg': 'Input should be an array or an object',+ 'input': 'invalid',+ 'ctx': {'class_name': 'Point'},+ }+ ]+++def test_namedtuple_missing_errors():+ """Missing fields use the index as location for positional inputs, and the field name for dict inputs."""++ class Point(NamedTuple):+ x: int+ y: int++ ta = TypeAdapter(Point)++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python([1])+ assert exc_info.value.errors(include_url=False) == [+ {'type': 'missing', 'loc': (1,), 'msg': 'Field required', 'input': [1]}+ ]++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python({'x': 1})+ assert exc_info.value.errors(include_url=False) == [+ {'type': 'missing', 'loc': ('y',), 'msg': 'Field required', 'input': {'x': 1}}+ ]+++def test_namedtuple_validation_alias():+ class Point(NamedTuple):+ x: Annotated[int, Field(validation_alias='ex')]+ y: int++ ta = TypeAdapter(Point)++ assert ta.validate_python({'ex': 1, 'y': 2}) == Point(1, 2)+ # The alias only applies to dict inputs, positional inputs are unaffected:+ assert ta.validate_python((1, 2)) == Point(1, 2)++ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python({'x': 1, 'y': 2})+ assert exc_info.value.errors(include_url=False) == [+ {'type': 'missing', 'loc': ('ex',), 'msg': 'Field required', 'input': {'x': 1, 'y': 2}},+ {'type': 'extra_forbidden', 'loc': ('x',), 'msg': 'Extra inputs are not permitted', 'input': 1},+ ]+++def test_namedtuple_mapping_input():+ class Map(Mapping):+ def __init__(self, **kwargs):+ self._d = kwargs++ def __iter__(self):+ return iter(self._d)++ def __len__(self) -> int:+ return len(self._d)++ def __getitem__(self, k, /):+ return self._d[k]++ class Point(NamedTuple):+ x: int+ y: int++ assert TypeAdapter(Point).validate_python(Map(x=1, y=2)) == Point(1, 2)+++def test_namedtuple_other_class_converted():+ """Instances of other named tuple classes are treated as regular tuples (positional)."""++ class A(NamedTuple):+ x: int++ class B(NamedTuple):+ x: int++ validated = TypeAdapter(A).validate_python(B(x=1))+ assert type(validated) is A+++def test_namedtuple_serialization():+ class Point(NamedTuple):+ x: int+ y: str++ ta = TypeAdapter(Point)++ dumped = ta.dump_python(Point(1, 'a'))+ assert dumped == (1, 'a')+ assert type(dumped) is tuple+ assert ta.dump_python(Point(1, 'a'), mode='json') == [1, 'a']+ assert ta.dump_json(Point(1, 'a')) == b'[1,"a"]'++ # Any tuple is accepted:+ assert ta.dump_python((1, 'a')) == (1, 'a')+++def test_namedtuple_serialization_warnings():+ class Point(NamedTuple):+ x: int+ y: str++ ta = TypeAdapter(Point)++ with pytest.warns(UserWarning, match='Expected `Point` - serialized value may not be as expected'):+ assert ta.dump_python('not a tuple') == 'not a tuple'+ with pytest.warns(UserWarning, match='Unexpected extra items present in named tuple'):+ assert ta.dump_python((1, 'a', 'extra')) == (1, 'a')+ with pytest.warns(UserWarning, match='Unexpected too few items present in named tuple'):+ assert ta.dump_python((1,)) == (1,)+++def test_namedtuple_serialization_include_exclude():+ class Point(NamedTuple):+ x: int+ y: str++ ta = TypeAdapter(Point)++ assert ta.dump_python(Point(1, 'a'), include={0}) == (1,)+ assert ta.dump_python(Point(1, 'a'), exclude={0}) == ('a',)+ assert ta.dump_json(Point(1, 'a'), include={0}) == b'[1]'+++def test_namedtuple_as_dict_key_serialization():+ class Point(NamedTuple):+ x: int+ y: str++ ta = TypeAdapter(dict[Point, int])+ assert ta.dump_json({Point(1, 'a'): 2}) == b'{"1,a":2}'+++def test_namedtuple_union_serialization_preserves_class():+ """In unions, the value must be an instance of the named tuple class for the member to match."""++ class A(NamedTuple):+ x: Annotated[int, PlainSerializer(lambda v: v + 1)]++ class B(NamedTuple):+ x: Annotated[int, PlainSerializer(lambda v: v + 2)]++ ta = TypeAdapter(A | B)+ assert ta.dump_json(A(0)) == b'[1]'+ assert ta.dump_json(B(0)) == b'[2]'