Backtestspydanticrun-20261002-175417#11925
ValidationError for NamedTuple attributes does not include the attribute name when using from_attributes=True
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches fix the reported symptom: a namedtuple instance validated via from_attributes now reports `('tup', 'number')` instead of `('tup', 1)`.
Patch A makes a targeted change in ArgumentsValidator. When the Python input is a namedtuple instance (a tuple subclass whose type has `_fields`), positional errors use the parameter name instead of the index. Plain tuples and lists keep index locations. Its tests cover the exact issue scenario (from_attributes), a dict containing a namedtuple instance, a dict input, another namedtuple class, the plain-tuple fallback, and a generic namedtuple. It also adds a core-level test. These tests would fail before the change and pass after.
Patch B replaces the namedtuple's call/arguments core schema with a new 'named-tuple' schema, validator, serializer, error type, JSON schema handler and docs. This is a broad redesign with real user-facing behaviour changes beyond the issue:
- Extra positional items now raise `too_long` instead of `unexpected_positional_argument`.
- Extra dict keys now raise `extra_forbidden` instead of `unexpected_keyword_argument`.
- Invalid input raises a new `named_tuple_type` error instead of `arguments_type`.
- The core schema shape changes, which breaks user `__get_pydantic_core_schema__` hooks that touch `schema['arguments_schema']`. The patch had to rewrite `test_namedtuple_modify_schema` because of this.
- It deletes and relocates the existing test file, rewriting expected outputs to match the new behaviour.
- It adds ~600 lines of new Rust serializer and validator code.
That churn adds substantial regression and compatibility risk and obscures the fix itself. The extra scope earns no credit.
On correctness for the issue, both work. On tests, both are adequate. On scope and risk, A is clearly better.
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
18m 30s
Wall-clock time in the container
Full test suite
No new failures
12,299 passed · 499 skipped · 12,798 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
130vs 1,755 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
When using either the from_attributes=True in the model config or as an argument to the model_validate function, any ValidationError that is raised from a field validator on a NamedTuple's field does not include the attribute name. Instead, it seems to include the attribute's position within the tuple.
If I instead use model_validate and pass a dictionary, the ValidationError from the NamedTuple's field validator contains the attribute's name.
For example:
... ExampleModel.model_validate(SomeOtherInput(), from_attributes=True)
...
Traceback (most recent call last):
File "<python-input-0>", line 16, in <module>
ExampleModel.model_validate(SomeOtherInput(), from_attributes=True)
~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/rccausey/.cache/pypoetry/virtualenvs/billing-api--M5yUIBR-py3.13/lib/python3.13/site-packages/pydantic/main.py", line 703, in model_validate
return cls.__pydantic_validator__.validate_python(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
obj, strict=strict, from_attributes=from_attributes, context=context, by_alias=by_alias, by_name=by_name
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
pydantic_core._pydantic_core.ValidationError: 1 validation error for ExampleModel
tuple_attr.1
Input should be greater than 0 [type=greater_than, input_value=0, input_type=int]
For further information visit https://errors.pydantic.dev/2.11/v/greater_than
>>> ExampleModel.model_validate({"tuple_attr": {"alarm_type_id": "alarmtype_asdf", "sequence_number": 0}})
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
ExampleModel.model_validate({"tuple_attr": {"alarm_type_id": "alarmtype_asdf", "sequence_number": 0}})
~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/rccausey/.cache/pypoetry/virtualenvs/billing-api--M5yUIBR-py3.13/lib/python3.13/site-packages/pydantic/main.py", line 703, in model_validate
return cls.__pydantic_validator__.validate_python(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
obj, strict=strict, from_attributes=from_attributes, context=context, by_alias=by_alias, by_name=by_name
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
pydantic_core._pydantic_core.ValidationError: 1 validation error for ExampleModel
tuple_attr.sequence_number
Input should be greater than 0 [type=greater_than, input_value=0, input_type=int]
For further information visit https://errors.pydantic.dev/2.11/v/greater_than
>>>
Example Code
from typing import Annotated, NamedTuple
from pydantic import BaseModel, Field
class ExampleTuple(NamedTuple):
alarm_type_id: Annotated[str, Field(pattern=r"^alarmtype_.*$")]
sequence_number: Annotated[int, Field(gt=0)]
class ExampleModel(BaseModel):
tuple_attr: ExampleTuple
class SomeOtherInput:
def __init__(self):
self.tuple_attr = ExampleTuple(alarm_type_id="alarmtype_JtHRjBKie01iOss0KoUul10RzD9", sequence_number=0)
ExampleModel.model_validate(SomeOtherInput(), from_attributes=True)
Python, Pydantic & OS Version
pydantic version: 2.11.3
pydantic-core version: 2.33.1
pydantic-core build: profile=release pgo=false
install path: /home/rccausey/.cache/pypoetry/virtualenvs/billing-api--M5yUIBR-py3.13/lib/python3.13/site-packages/pydantic
python version: 3.13.3 (main, May 21 2025, 10:47:46) [GCC 11.4.0]
platform: Linux-6.6.87.1-microsoft-standard-WSL2-x86_64-with-glibc2.35
related packages: typing_extensions-4.12.2
commit: unknownThe two patches
pydantic-core/src/validators/arguments.rsindex 23a01568..1df56650 100644@@ -209,6 +209,13 @@ impl Validator for ArgumentsValidator { let pos_args = args.args(); let kw_args = args.kwargs(); + // when validating a namedtuple instance, its items are attributes with names, so use the+ // parameter name rather than the positional index in error locations+ let pos_loc_by_name = match input.as_python() {+ Some(py_input) => is_namedtuple_instance(py_input)?,+ None => false,+ };+ // go through arguments getting the value from args or kwargs and validating it for (index, parameter) in self.parameters.iter().enumerate() { let mut pos_value = None;@@ -240,7 +247,15 @@ impl Validator for ArgumentsValidator { (Some(pos_value), None) => match parameter.validator.validate(py, pos_value.borrow_input(), state) { Ok(value) => output_args.push(value), Err(ValError::LineErrors(line_errors)) => {- errors.extend(line_errors.into_iter().map(|err| err.with_outer_location(index)));+ if pos_loc_by_name {+ errors.extend(+ line_errors+ .into_iter()+ .map(|err| err.with_outer_location(parameter.name.clone())),+ );+ } else {+ errors.extend(line_errors.into_iter().map(|err| err.with_outer_location(index)));+ } } Err(err) => return Err(err), },@@ -400,3 +415,11 @@ impl Validator for ArgumentsValidator { Self::EXPECTED_TYPE } }++/// Whether `obj` is an instance of a namedtuple class, i.e. a `tuple` subclass with a `_fields` attribute.+fn is_namedtuple_instance(obj: &Bound<'_, PyAny>) -> PyResult<bool> {+ if !obj.is_instance_of::<PyTuple>() || obj.is_exact_instance_of::<PyTuple>() {+ return Ok(false);+ }+ obj.get_type().hasattr(intern!(obj.py(), "_fields"))+}pydantic-core/tests/validators/test_arguments.pyindex 444865ce..1e4be48c 100644@@ -1219,3 +1219,36 @@ def test_by_alias_and_name_config_interaction( (), {'my_field': 1}, )+++def test_namedtuple_input_error_loc_uses_parameter_name():+ from collections import namedtuple++ Point = namedtuple('Point', 'x y')++ v = SchemaValidator(+ cs.arguments_schema(+ [+ cs.arguments_parameter(name='x', schema=cs.int_schema()),+ cs.arguments_parameter(name='y', schema=cs.int_schema()),+ ]+ )+ )++ assert v.validate_python(Point(1, '2')) == ((1, 2), {})++ with pytest.raises(ValidationError) as exc_info:+ v.validate_python(Point(1, 'a'))+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'int_parsing',+ 'loc': ('y',),+ 'msg': 'Input should be a valid integer, unable to parse string as an integer',+ 'input': 'a',+ }+ ]++ # plain tuples are still reported by position+ with pytest.raises(ValidationError) as exc_info:+ v.validate_python((1, 'a'))+ assert exc_info.value.errors(include_url=False)[0]['loc'] == (1,)tests/test_types_namedtuple.pyindex 7c72db4d..129cc7d0 100644@@ -254,3 +254,75 @@ def test_namedtuple_inheritance_with_annotations(): 'input': 'c', } ]+++class _GtZeroTuple(NamedTuple):+ name: str+ number: PositiveInt+++def test_namedtuple_instance_error_loc_uses_field_names() -> None:+ """https://github.com/pydantic/pydantic/issues/11878"""++ class Model(BaseModel):+ tup: _GtZeroTuple++ expected = [+ {+ 'type': 'greater_than',+ 'loc': ('tup', 'number'),+ 'msg': 'Input should be greater than 0',+ 'input': 0,+ 'ctx': {'gt': 0},+ }+ ]++ class FromAttributesInput:+ tup = _GtZeroTuple(name='a', number=0)++ with pytest.raises(ValidationError) as exc_info:+ Model.model_validate(FromAttributesInput(), from_attributes=True)+ assert exc_info.value.errors(include_url=False) == expected++ with pytest.raises(ValidationError) as exc_info:+ Model.model_validate({'tup': _GtZeroTuple(name='a', number=0)})+ assert exc_info.value.errors(include_url=False) == expected++ with pytest.raises(ValidationError) as exc_info:+ Model.model_validate({'tup': {'name': 'a', 'number': 0}})+ assert exc_info.value.errors(include_url=False) == expected++ class OtherTuple(NamedTuple):+ first: str+ second: int++ # Instances of other namedtuples use the target field names:+ with pytest.raises(ValidationError) as exc_info:+ Model.model_validate({'tup': OtherTuple(first='a', second=0)})+ assert exc_info.value.errors(include_url=False) == expected++ # Plain tuples are still validated positionally:+ with pytest.raises(ValidationError) as exc_info:+ Model.model_validate({'tup': ('a', 0)})+ assert exc_info.value.errors(include_url=False)[0]['loc'] == ('tup', 1)++ assert Model.model_validate({'tup': _GtZeroTuple(name='a', number=1)}).tup == _GtZeroTuple('a', 1)+++def test_generic_namedtuple_instance_error_loc_uses_field_names() -> None:+ T = TypeVar('T')++ class Generic2DTuple(TypingExtensionsNamedTuple, Generic[T]):+ x: T+ y: T++ with pytest.raises(ValidationError) as exc_info:+ TypeAdapter(Generic2DTuple[int]).validate_python(Generic2DTuple(1, 'a'))+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'int_parsing',+ 'loc': ('y',),+ 'msg': 'Input should be a valid integer, unable to parse string as an integer',+ 'input': 'a',+ }+ ]
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]'