Skip to content

Can't initialize frozen dataclass properties in __init__ #7106

@Stiivi

Description

@Stiivi

I assume this is rather a missing feature than a bug.

The __init__() in the following code is offensive:

from dataclasses import dataclass
from typing import Optional

@dataclass(init=False, frozen=True)
class Thing:
    name: str
    key: str

    def __init__(self, name: str, key: Optional[str]=None) -> None:
        self.name = name
        self.key = key or name

The output is:

test.py:10: error: Property "name" defined in "Thing" is read-only
test.py:11: error: Property "key" defined in "Thing" is read-only

The error follows the frozen=True flag, although I would expect to be able to initialize the properties in the __init__() (or __post_init__()) function.

MyPy version: 0.711.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions