Skip to content

Root models are sometimes inferred as unions by mypy when using the mypy plugin #11675

@airwoodix

Description

@airwoodix

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Maybe related to #11657.

In the example below, Pyright 1.1.398 deduces A for both b.a and c.a, while mypy (with the Pydantic plugin) deduces the union type for c.a (but not in the simpler b.a case).

The problem appeared with Pydantic 2.11. It is not present with Pydantic 2.10.6. It is also not present when not using the Pydantic mypy plugin with Pydantic 2.11.

Example Code

from typing import reveal_type

from pydantic import RootModel, BaseModel


class A(RootModel[list[int]]):
    pass


class B(BaseModel):
    a: A


class C(B):
    pass


b = B(a=A([1, 2, 3]))
c = C(a=A([1, 2, 3]))

reveal_type(b.a)  # A (expected)
reveal_type(c.a)  # A | list[int] (unexpected, should be A)

Python, Pydantic & OS Version

pydantic version: 2.11.1
pydantic-core version: 2.33.0
pydantic-core build: profile=release pgo=false

python version: 3.12.2 (main, Feb 25 2024, 04:38:01) [Clang 17.0.6 ]
platform: Linux-6.8.0-57-generic-x86_64-with-glibc2.39
related packages: typing_extensions-4.12.2 mypy-1.15.0

Metadata

Metadata

Assignees

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