Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
sisp opened this issue Jun 22, 2021 · 3 comments
Closed

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

sisp opened this issue Jun 22, 2021 · 3 comments

Comments

@sisp
Copy link

sisp commented Jun 22, 2021

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.

@sisp sisp added the feature label Jun 22, 2021
@erictraut
Copy link

As a simple workaround, you could assign it a field descriptor.

@dataclass
class A:
    x: Final[str] = field()

@sisp
Copy link
Author

sisp commented Jun 22, 2021

@erictraut Thanks for suggesting the workaround! A proper fix would still be nice.

@AlexWaygood
Copy link
Member

Closing as a duplicate of #5608

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants