Skip to content

Allow Final attributes declared in dataclass body without a default value #10688

Closed
@sisp

Description

@sisp

Feature

It should be allowed to declare a read-only (final) dataclass attribute:

@dataclass
class A:
    x: Final[str]  # error: Final name must be initialized with a value  [misc]

Pitch

I think it's a common scenario where a dataclass attribute should be read-only once the dataclass has been instantiated. It works fine with a default value

@dataclass
class B:
    x: Final[str] = 'abc'  # ok

and with a regular class:

class B:
    x: Final[str]  # ok
    
    def __init__(self, x: str) -> None:
        self.x = x

See the full example on the mypy playground.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions