Skip to content

Bug: false Unexpected keyword argument in pydantic.mypy plugin (in very specific case) #11329

@tlambert03

Description

@tlambert03

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Summary: In a particular scenario using a base class with ConfigDict(extra="forbid"), recursive models (in my case with tagged unions) can result in a false Unexpected keyword argument mypy error on the subclasses.

Example code

This issue is best explained demonstrated with an actual repo, so I created a mwe repo (which models a simple node graph) here: https://github.com/tlambert03/pydantic-mypy-err

git clone https://github.com/tlambert03/pydantic-mypy-err.git
cd pydantic-mypy-err

pip install mypy==1.14.1 pydantic==2.10.5
mypy example.py

Apologies that this can't be summed up in a simpler example, but hopefully that MWE should immediately demonstrate the problem and allow you to play with some variations.

This file contains the most interesting config, and is reproduced here:

from typing import TYPE_CHECKING, Annotated, ClassVar

from pydantic import BaseModel, ConfigDict, Field

if TYPE_CHECKING:
    from .circle import Circle

    # note, if square were defined after Node in THIS file, mypy is happy.
    from .square import Square


class _MyBase(BaseModel):
    """Base class for all evented pydantic-style models."""

    # Note: without this additional base with extra="forbid" mypy is happy.
    model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")


AnyNode = Annotated["Circle | Square", Field(discriminator="node_type")]


class Node(_MyBase):
    name: str | None = Field(default=None, description="Name of the node.")
    parent: AnyNode | None = None

Python, Pydantic & OS Version

pydantic version: 2.10.5
        pydantic-core version: 2.27.2
          pydantic-core build: profile=release pgo=false
                 install path: /Users/talley/Desktop/pydantic-mypy-err/.venv/lib/python3.12/site-packages/pydantic
               python version: 3.12.7 (main, Oct 16 2024, 07:12:08) [Clang 18.1.8 ]
                     platform: macOS-15.2-arm64-arm-64bit
             related packages: mypy-1.14.1 typing_extensions-4.12.2
                       commit: unknown

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V2Bug related to Pydantic V2topic-mypy pluginRelated to the mypy plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions