Skip to content

Root model classes are considered as an union type by mypy #11657

@antoniogamizdelgado

Description

@antoniogamizdelgado

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

After upgrading to pydantic 2.11.0, our mypy pre-commit check started considering root models as union type instead of just a root model instance.
After checking release notes, I think this is related to #11212, but not sure.

This only happens when using mypy with the pydantic plugin. In our mypy.ini config we have:

[mypy]
plugins = pydantic.mypy, mypy_django_plugin.main

Downgrading to pydantic 2.10.6 fixes the issue.

Example Code

class FieldName(RootModel[str]):
    def __str__(self) -> str:
        return self.root

    def __hash__(self) -> int:
        return hash(self.root)

field_name = FieldName("value")

print(field_name.root) #  error: Item "str" of "FieldName | str" has no attribute "root"  [union-attr]

Python, Pydantic & OS Version

pydantic version: 2.10.6
        pydantic-core version: 2.27.2
          pydantic-core build: profile=release pgo=false
                 install path: /Users/antoniogamizdelgado/Library/Caches/pypoetry/virtualenvs/badger-go-p6YDoiKT-py3.12/lib/python3.12/site-packages/pydantic
               python version: 3.12.4 (main, Jul  1 2024, 14:55:58) [Clang 15.0.0 (clang-1500.3.9.4)]
                     platform: macOS-15.3.2-arm64-arm-64bit
             related packages: mypy-1.11.2 typing_extensions-4.13.0
                       commit: unknown

We had to downgrade to 2.10.6 to avoid the error.

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