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 omitting initializer for Final attributes in dataclasses #5608

Open
ilevkivskyi opened this issue Sep 12, 2018 · 2 comments
Open

Allow omitting initializer for Final attributes in dataclasses #5608

ilevkivskyi opened this issue Sep 12, 2018 · 2 comments

Comments

@ilevkivskyi
Copy link
Member

Dataclasses typically don't have __init__, so this is rejected, but is probably valid:

@dataclass
class C:
    x: int
    y: Final[int]

A possible solution is that plugin should set the final_set_in_init flag manually for the corresponding field Vars.

@jcrist
Copy link

jcrist commented Mar 25, 2023

I just ran into this. pyright allows these type annotations as is (Final indicates an instance variable), and discussion in python/cpython#89547 seems to indicate this is what'd be most ergonomic to support. It also matches how dataclasses itself handles these annotations.

For now, a workaround is to add # type: ignore on the annotation line. The dataclass definition still seems to be processed correctly, this just skips the error about a missing initializer.

import dataclasses
from typing import Final


@dataclasses.dataclass
class Test:
    # The `type: ignore` is needed here to avoid an error due to a missing
    # initializer
    x: Final[int]  # type: ignore


t = Test(1)  # Signature still inferred properly
reveal_type(t.x)
t2 = Test("bad")  # Which means mypy marks this as an error
$ mypy ex.py 
ex.py:13: note: Revealed type is "builtins.int"
ex.py:14: error: Argument 1 to "Test" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

For my own use cases, it'd be nice if the fix here also applied to the recent dataclass_tranform support, so this fix could work for other dataclass-like things as well.

@tmke8
Copy link
Contributor

tmke8 commented May 13, 2024

The typing spec now specifies that this should be allowed: python/typing#1669

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