← Back to index

dataclasses_final.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 5
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the handling of ClassVar and Final in dataclasses.
3"""
4
5from dataclasses import dataclass
6from typing import assert_type, ClassVar, Final
7
8# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics
9
10# > A final class variable on a dataclass must be explicitly annotated as
11# e.g. x: ClassVar[Final[int]] = 3.
14@dataclass
15class D:
16 final_no_default: Final[int]
17 final_with_default: Final[str] = "foo"
18 final_classvar: ClassVar[Final[int]] = 4
19 # we don't require support for Final[ClassVar[...]] because the dataclasses
20 # runtime implementation won't recognize it as a ClassVar either
23# An explicitly marked ClassVar can be accessed on the class:
24assert_type(D.final_classvar, int)
26# ...but not assigned to, because it's Final:
27D.final_classvar = 10 # E: can't assign to final attribute
[invalid-assignment] Cannot assign to final attribute `final_classvar` on type `<class 'D'>`
29# A non-ClassVar attribute (with or without default) is a dataclass field:
30d = D(final_no_default=1, final_with_default="bar")
31assert_type(d.final_no_default, int)
32assert_type(d.final_with_default, str)
34# ... but can't be assigned to (on the class or on an instance):
35d.final_no_default = 10 # E: can't assign to final attribute
[invalid-assignment] Cannot assign to final attribute `final_no_default` on type `D`
36d.final_with_default = "baz" # E: can't assign to final attribute
[invalid-assignment] Cannot assign to final attribute `final_with_default` on type `D`
37D.final_no_default = 10 # E: can't assign to final attribute
[invalid-assignment] Cannot assign to final attribute `final_no_default` on type `<class 'D'>`
38D.final_with_default = "baz" # E: can't assign to final attribute
[invalid-assignment] Cannot assign to final attribute `final_with_default` on type `<class 'D'>`