Backtestspydanticrun-20260929-204949#11925
ValidationError for NamedTuple attributes does not include the attribute name when using from_attributes=True
The merged fix was judged better than our patch.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches target the same symptom (positional index instead of field name in error locs for NamedTuple instances validated via from_attributes). Patch A is a minimal Python-side workaround: it wraps the existing `call_schema`/`arguments_schema` in a before-validator that converts NamedTuple instances to ArgsKwargs keyword arguments so errors surface field names. This masks the symptom rather than fixing the root cause and carries real risks: (a) it changes the shared `resolve_ref_schema` for ALL function-before/after/wrap schemas whose inner schema is a ref, not just namedtuples, which can affect user validators; and (b) it leaves the existing `test_namedtuple_modify_schema` untouched even though `handler(source)` now returns a function-before schema, so `schema['arguments_schema']` would KeyError — i.e. Patch A likely breaks an existing test it never updated. Patch B fixes the problem at its root by introducing a dedicated `named-tuple` core schema (validator + serializer + JSON schema + gather/traverse support), which validates positionally (index locs) for tuples/lists/JSON arrays, by name (field-name locs) for dicts, and by name for class instances — exactly the behavior the issue asks for. It adds a directly-on-point test (`test_namedtuple_from_attributes_error_locs`) plus comprehensive coverage of serialization, unions, aliases, missing/extra fields, and the new `named_tuple_type` error, and consistently updates the affected existing tests (right_length, inheritance, modify_schema) to the new, coherent behavior. Patch B is larger and touches the Rust core, but that breadth is the correct locus for the fix, is fully tested, and mirrors a principled redesign rather than a fragile shim. On correctness and tests Patch B is clearly stronger; the extra scope is justified and does not obscure the fix.
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
21m 49s53 turns
Wall-clock time in the container
Full test suite
No new failures
12,297 passed · 499 skipped · 12,796 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
69vs 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/_internal/_generate_schema.pyindex d52930dc..2d201f6f 100644@@ -41,6 +41,7 @@ from zoneinfo import ZoneInfo import typing_extensions from pydantic_core import ( MISSING,+ ArgsKwargs, CoreSchema, MultiHostUrl, PydanticCustomError,@@ -1567,8 +1568,22 @@ class GenerateSchema: ], metadata={'pydantic_js_prefer_positional_arguments': True}, )- schema = core_schema.call_schema(arguments_schema, namedtuple_cls, ref=namedtuple_ref)- return self.defs.create_definition_reference_schema(schema)+ call_schema = core_schema.call_schema(arguments_schema, namedtuple_cls, ref=namedtuple_ref)++ field_names = namedtuple_cls._fields++ def convert_named_tuple_to_kwargs(input_value: Any) -> Any:+ # When the input is a NamedTuple instance (e.g. via `from_attributes=True`),+ # convert it to keyword arguments so that validation errors reference field+ # names rather than positional indices. Plain tuples/lists are left as-is to+ # preserve their positional matching behavior.+ if isinstance(input_value, tuple) and hasattr(type(input_value), '_fields'):+ return ArgsKwargs((), dict(zip(field_names, input_value)))+ return input_value++ return core_schema.no_info_before_validator_function(+ convert_named_tuple_to_kwargs, self.defs.create_definition_reference_schema(call_schema)+ ) def _generate_parameter_schema( self,pydantic/_internal/_schema_generation_shared.pyindex ece84bd2..844963e2 100644@@ -123,4 +123,11 @@ class CallbackGetCoreSchemaHandler(GetCoreSchemaHandler): return definition elif maybe_ref_schema['type'] == 'definitions': return self.resolve_ref_schema(maybe_ref_schema['schema'])+ elif maybe_ref_schema['type'] in ('function-before', 'function-after', 'function-wrap') and (+ maybe_ref_schema['schema']['type'] in ('definition-ref', 'definitions')+ ):+ # Some schemas (e.g. named tuples) are wrapped in a transparent validator function+ # around a definition reference. Step through the wrapper to expose the referenced+ # schema, so callers relying on the underlying schema structure keep working.+ return self.resolve_ref_schema(maybe_ref_schema['schema']) return maybe_ref_schematests/test_types_namedtuple.pyindex 7c72db4d..afb4cbf0 100644@@ -1,10 +1,10 @@ from collections import namedtuple-from typing import Generic, NamedTuple, Optional, TypeVar+from typing import Annotated, Generic, NamedTuple, Optional, TypeVar import pytest from typing_extensions import NamedTuple as TypingExtensionsNamedTuple -from pydantic import BaseModel, ConfigDict, PositiveInt, TypeAdapter, ValidationError+from pydantic import BaseModel, ConfigDict, Field, PositiveInt, TypeAdapter, ValidationError from pydantic.errors import PydanticSchemaGenerationError @@ -119,6 +119,45 @@ def test_namedtuple_right_length(): ] +def test_namedtuple_from_attributes_error_loc():+ 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_x', sequence_number=0)++ with pytest.raises(ValidationError) as exc_info:+ ExampleModel.model_validate(SomeOtherInput(), from_attributes=True)+ # insert_assert(exc_info.value.errors(include_url=False))+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'greater_than',+ 'loc': ('tuple_attr', 'sequence_number'),+ 'msg': 'Input should be greater than 0',+ 'input': 0,+ 'ctx': {'gt': 0},+ }+ ]++ with pytest.raises(ValidationError) as exc_info:+ ExampleModel.model_validate({'tuple_attr': {'alarm_type_id': 'alarmtype_x', 'sequence_number': 0}})+ # insert_assert(exc_info.value.errors(include_url=False))+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'greater_than',+ 'loc': ('tuple_attr', 'sequence_number'),+ 'msg': 'Input should be greater than 0',+ 'input': 0,+ 'ctx': {'gt': 0},+ }+ ]++ def test_namedtuple_postponed_annotation(): """ https://github.com/pydantic/pydantic/issues/2760
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]'
What the agent reported
The review confirms the fix is correct and safely scoped. The change is complete.
Summary
What was wrong
When a BaseModel field is typed as a NamedTuple, validating with from_attributes=True passes the actual NamedTuple instance (a tuple) to the namedtuple's call_schema/arguments_schema. pydantic-core matches tuple input positionally, so a nested field's ValidationError reported the tuple index (('tuple_attr', 1)) instead of the field name (('tuple_attr', 'sequence_number')). Dict input already matched by keyword and reported names correctly. arguments_v3 has the same index-for-positional behavior, so the only way to get name-based locs is to feed the arguments validator keyword input.
What I changed
pydantic/_internal/_generate_schema.py—_namedtuple_schemanow wraps the namedtuplecall_schema(registered as a definition reference) in ano_info_before_validator_function. When the input is aNamedTupleinstance (isinstance(v, tuple) and hasattr(type(v), '_fields')), it is converted to keyword argsArgsKwargs((), dict(zip(field_names, v))), so the arguments validator matches by name and error locs use field names. Plain tuples/lists are left untouched, preserving their positional behavior (sotest_namedtuple_right_length'sunexpected_positional_argumentstill fires). AddedArgsKwargsto thepydantic_coreimport.pydantic/_internal/_schema_generation_shared.py—CallbackGetCoreSchemaHandler.resolve_ref_schemanow also steps through afunction-before/after/wrapwrapper whose inner schema is adefinition-ref/definitions. This was required because the new wrapper otherwise hid thecall_schemafrom custom__get_pydantic_core_schema__handlers that callhandler(source)and indexschema['arguments_schema'](existingtest_namedtuple_modify_schema). The condition is narrow: normal user before/after/wrap validators wrap inline schemas (not bare definition-refs) and are unaffected; discriminated-union callers guard ondefinition-reffirst.tests/test_types_namedtuple.py— addedtest_namedtuple_from_attributes_error_loc, which reproduces the report exactly and asserts the name-based loc for both thefrom_attributes=Trueinstance path and the dict path.
Test evidence
- The new regression test failed before the fix (
locwas('tuple_attr', 1)) and passes after. ./bt-test tests/test_types_namedtuple.py tests/test_json_schema.py tests/test_validators.py: 720 passed, onlytest_v1_validator_deprecatedfailed — which I verified fails identically on the clean tree (it asserts a warning filename equals__file__, failing on the container's/workvs/workspacepath mapping; unrelated to this change).- Broad
uv run pytestacross json_schema, dataclasses, generics, validators, type_adapter, main, config, edge_cases, root_model, validate_call, serialize, typeddict, namedtuple: 2175 passed (same one pre-existing environmental failure). - Manual repro:
from_attributesnow yields('tuple_attr', 'sequence_number'); valid instances round-trip and serialize; dict path unchanged; plain-list input still positional.
Requirements disposition
- ValidationError for NamedTuple must include the attribute name (not position) when using
from_attributes=True— ✅ Implemented and covered by the new regression test (fails before, passes after). - Dict-input path must keep reporting the field name — ✅ Preserved; asserted by the second half of the regression test.
- "I confirm I'm using Pydantic V2" checkbox — N/A (informational; this repo is Pydantic V2).
Known minor, in-scope limitations (documented by review, none contradicting the report): a nested/recursive namedtuple value that is itself an instance still reports positionally (report's scenario is top-level and is fixed); a namedtuple with a custom __get_pydantic_core_schema__ returning handler(source) opts out of the conversion; passing an unrelated oversized namedtuple instance now truncates rather than raising unexpected_positional_argument. All changes are left as uncommitted working-tree edits.