Skip to content

Cannot inherit frozen dataclass from a non-frozen one error when using pydantic frozen=True #14857

Closed

Description

@johnnyleitrim

Bug Report

Specifying frozen=True as model class kwargs for pydantic models causes the following error to be emitted from mypy:

Cannot inherit frozen dataclass from a non-frozen one

To Reproduce

  1. Install pydantic and mypy: pip install pydantic mypy
  2. Create test.py with the following content:
from pydantic import BaseModel

class MyModel(BaseModel, frozen=True):
    my_val: int
  1. Run mypy on the test file: mypy test.py

Expected Behavior
No errors reported (as was the case with mypy 1.0.1):

> mypy test.py
Success: no issues found in 1 source file

Actual Behavior
Errors reported:

> mypy test.py
test.py:3: error: Cannot inherit frozen dataclass from a non-frozen one  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.1.1
  • Python version used: 3.10

Activity

  1. wesleywright commented on Mar 10, 2023

    @wesleywright
    Collaborator

    Similar to in #14850, I believe this is actually an issue with the Pydantic library's use of dataclass_transform. From looking at the code, it seems that BaseModel is itself using the transform and should be treated as a dataclass, so per the standard, frozen dataclasses cannot subclass it.

    You may be able to use the same workaround as suggested in #14850 (using the latest version of the Pydantic plugin).

  2. wesleywright commented on Mar 10, 2023

    @wesleywright
    Collaborator

    After double checking the spec (whoops), there is actually a provision for this:

    Frozen dataclasses cannot inherit from non-frozen dataclasses. A class that has been decorated with dataclass_transform is considered neither frozen nor non-frozen, thus allowing frozen classes to inherit from it. Similarly, a class that directly specifies a metaclass that is decorated with dataclass_transform is considered neither frozen nor non-frozen.

    This seems to be the only way to declare a class that has dataclass semantics but which is treated as neither frozen nor non-frozen. This is definitely a bug in MyPy; I will try to create a PR to fix it.

  3. added a commit that references this issue on Mar 15, 2023
    a6b5b1e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions