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

Bare Final special form with dataclasses #9468

Open
Viicos opened this issue Nov 15, 2024 · 3 comments
Open

Bare Final special form with dataclasses #9468

Viicos opened this issue Nov 15, 2024 · 3 comments
Labels
bug Something isn't working

Comments

@Viicos
Copy link

Viicos commented Nov 15, 2024

Using a bare Final special form with a default value, pyright will not assume it is a normal field (probably because it assumes it is a ClassVar?):

Code sample in pyright playground

from typing import Final

from dataclasses import dataclass

@dataclass
class A:
    a: Final = 1
    b: Final[int] = 1


reveal_type(A.__init__)
# "(self: A, b: int = 1) -> None"

However, mypy seems to include a as a field (playground).

Seems like the conformance tests don't cover this use case, so it might have been an oversight.

@LeeeeT
Copy link

LeeeeT commented Nov 15, 2024

I wonder why python even includes a Final field into the __init__ 🤔

@Viicos
Copy link
Author

Viicos commented Nov 15, 2024

This was clarified in the typing specification here. You can read more about the semantics of the Final special form here. While class variables are not included in the __init__ (because they shouldn't change per instance), Final (in the context of a class) means the value can't change after the class have been instantiated.

@vtgn
Copy link

vtgn commented Nov 18, 2024

I wonder why python even includes a Final field into the __init__ 🤔

In Java for example, you can declare an attribute as Final and define it either directly on the same line, or else in the constructor. Defining the value in the constructor is very useful to be able to set the final attribute with a calculated value. It's cool Python chose to do the same, but the linters are not uptodate yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants