Skip to content

Mypy type checking not working properly for classes that inherit properties after v2.6.4 #9007

@pengelsman7

Description

@pengelsman7

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

In v2.6.3 I had lines of code that rightfully needed type checking or mypy ignores for union-attr since the fields were typed like <type> | None. However, after I upgraded to v2.6.4 mypy is now telling me many of these type ignores are no longer necessary even though I didn't change my code at all. It seems to only be happening for classes that inherit from another model as you can see from my example. Anything that is just a BaseModel class seems to still require the type checking. I imagine its probably related to the change in this PR?

Example Code

from pydantic import BaseModel class Foo(BaseModel): id: int | None class Bar(BaseModel): foo: Foo | None class Baz(Bar): name: str b = Bar(foo={"id": 1}) z = Baz(foo={"id": 1}, name="test") assert z.foo.id == 1 # needed an ignore before assert b.foo.id == 1 # type: ignore[union-attr]

Python, Pydantic & OS Version

pydantic version: 2.6.4 pydantic-core version: 2.16.3 pydantic-core build: profile=release pgo=false install path: /fn/lib/venv/lib/python3.11/site-packages/pydantic python version: 3.11.8 (main, Mar 10 2024, 01:11:42) [GCC 10.2.1 20210110] platform: Linux-6.5.13-orbstack-00122-g57b8027e2387-aarch64-with-glibc2.31 related packages: typing_extensions-4.9.0 commit: unknown 

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V2Bug related to Pydantic V2pendingIs unconfirmed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions