You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allow omitting initializer for Final attributes in dataclasses #5608
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.
importdataclassesfromtypingimportFinal@dataclasses.dataclassclassTest:
# The `type: ignore` is needed here to avoid an error due to a missing# initializerx: Final[int] # type: ignoret=Test(1) # Signature still inferred properlyreveal_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.
Activity
jcrist commentedon Mar 25, 2023
I just ran into this.
pyrightallows these type annotations as is (Finalindicates an instance variable), and discussion in python/cpython#89547 seems to indicate this is what'd be most ergonomic to support. It also matches howdataclassesitself handles these annotations.For now, a workaround is to add
# type: ignoreon the annotation line. The dataclass definition still seems to be processed correctly, this just skips the error about a missing initializer.For my own use cases, it'd be nice if the fix here also applied to the recent
dataclass_tranformsupport, so this fix could work for other dataclass-like things as well.tmke8 commentedon May 13, 2024
The typing spec now specifies that this should be allowed: python/typing#1669
Add support for Final[...] in dataclasses (python#21334)