Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reflect namedtuple default values during validation #7144

Merged
merged 1 commit into from Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion pydantic/_internal/_generate_schema.py
Expand Up @@ -1130,7 +1130,9 @@ def _namedtuple_schema(self, namedtuple_cls: Any, origin: Any) -> core_schema.Co

arguments_schema = core_schema.arguments_schema(
[
self._generate_parameter_schema(field_name, annotation)
self._generate_parameter_schema(
field_name, annotation, default=namedtuple_cls._field_defaults.get(field_name, Parameter.empty)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though this looks like a private attribute access, this _field_defaults attribute is explicitly present in the type stubs for NamedTuple — I think it's intended for public access, just has an underscore to prevent name collisions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

@Viicos Viicos Aug 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

)
for field_name, annotation in annotations.items()
],
metadata=build_metadata_dict(js_prefer_positional_arguments=True),
Expand Down
9 changes: 9 additions & 0 deletions tests/test_types_namedtuple.py
Expand Up @@ -199,3 +199,12 @@ class MyNamedTuple(TypingExtensionsNamedTuple, Generic[T]):
'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)