Skip to content

Commit c605579

Browse files
authored
Do not allow to use Final and ClassVar at same time (#10478)
1 parent 675ae1a commit c605579

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

mypy/semanal.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2295,6 +2295,11 @@ def unwrap_final(self, s: AssignmentStmt) -> bool:
22952295
self.fail("Type in Final[...] can only be omitted if there is an initializer", s)
22962296
else:
22972297
s.type = s.unanalyzed_type.args[0]
2298+
2299+
if s.type is not None and self.is_classvar(s.type):
2300+
self.fail("Variable should not be annotated with both ClassVar and Final", s)
2301+
return False
2302+
22982303
if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], RefExpr):
22992304
self.fail("Invalid final declaration", s)
23002305
return False

test-data/unit/check-final.test

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,3 +1082,12 @@ class A:
10821082
self.x = 10 # type: Final
10831083
undefined # type: ignore
10841084
[builtins fixtures/tuple.pyi]
1085+
1086+
[case testFinalUsedWithClassVar]
1087+
from typing import Final, ClassVar
1088+
1089+
class A:
1090+
a: Final[ClassVar[int]] # E: Variable should not be annotated with both ClassVar and Final
1091+
b: ClassVar[Final[int]] # E: Final can be only used as an outermost qualifier in a variable annotation
1092+
c: ClassVar[Final] = 1 # E: Final can be only used as an outermost qualifier in a variable annotation
1093+
[out]

0 commit comments

Comments
 (0)