Skip to content

NamedTuple parameter resolution does not match constructor #7987

@NCPlayz

Description

@NCPlayz

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Since the NamedTuple parameter resolution relies on typing.get_type_hints, it produces unexpected results for the parameters. This is because when creating a NamedTuple the constructor is formed from the original annotations, regardless of it being inherited, whereas get_type_hints retrieves all type hints including bases. Is this intended behaviour?

Results from code below:

[{'name': 'test',
  'schema': {'metadata': {'pydantic.internal.needs_apply_discriminated_union': False},
             'type': 'str'}},
 {'name': 'test2',
  'schema': {'metadata': {'pydantic.internal.needs_apply_discriminated_union': False},
             'type': 'str'}},
 {'name': 'test3',
  'schema': {'metadata': {'pydantic.internal.needs_apply_discriminated_union': False},
             'type': 'str'}}]
Traceback (most recent call last):
  File "test.py", line 182, in <module>
    Bar(test="test", test2="test2", test3="test3")
TypeError: Foo.__new__() got an unexpected keyword argument 'test3'

Example Code

from typing import NamedTuple
import pprint

class Foo(NamedTuple):
    test: str
    test2: str

class Bar(Foo):
    test3: str

pprint.pprint(TypeAdapter(Bar).core_schema['arguments_schema']['arguments_schema'])
Bar(test="test", test2="test2", test3="test3")

Python, Pydantic & OS Version

        pydantic version: 2.4.2 (main branch at 60c5db6e1ea55d4e5fc13234810d513b3b1b03ae)
        pydantic-core version: 2.11.0
          pydantic-core build: profile=release pgo=true
                 install path: /repos/pydantic/pydantic
               python version: 3.12.0 | packaged by conda-forge | (main, Oct  3 2023, 08:43:22) [GCC 12.3.0]
                     platform: Linux
             related packages: mypy-1.1.1 email-validator-2.0.0.post2 typing_extensions-4.7.1 pydantic-extra-types-2.1.0 pydantic-settings-2.0.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V2Bug related to Pydantic V2

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions