From 30a95a16d0e0e9ddf89c00c559dae7354163b5b0 Mon Sep 17 00:00:00 2001 From: Yurii Karabas <1998uriyyo@gmail.com> Date: Sat, 15 May 2021 21:14:50 +0300 Subject: [PATCH 1/2] Do not allow use Final and ClassVar at same time --- mypy/semanal.py | 5 +++++ test-data/unit/check-final.test | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/mypy/semanal.py b/mypy/semanal.py index f157c795d9393..59d68421beab6 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -2295,6 +2295,11 @@ def unwrap_final(self, s: AssignmentStmt) -> bool: self.fail("Type in Final[...] can only be omitted if there is an initializer", s) else: s.type = s.unanalyzed_type.args[0] + + if s.type is not None and self.is_classvar(s.type): + self.fail("Variable should not be annotated with both ClassVar and Final", s) + return False + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], RefExpr): self.fail("Invalid final declaration", s) return False diff --git a/test-data/unit/check-final.test b/test-data/unit/check-final.test index 6f4077d9cff86..20c0591bb1356 100644 --- a/test-data/unit/check-final.test +++ b/test-data/unit/check-final.test @@ -1082,3 +1082,10 @@ class A: self.x = 10 # type: Final undefined # type: ignore [builtins fixtures/tuple.pyi] + +[case testFinalUsedWithClassVar] +from typing import Final, ClassVar + +class A: + a: Final[ClassVar[int]] # E: Variable should not be annotated with both ClassVar and Final +[out] \ No newline at end of file From dd80df8609c8a2b955367f5c49f0bcc3a475d999 Mon Sep 17 00:00:00 2001 From: Yurii Karabas <1998uriyyo@gmail.com> Date: Sun, 16 May 2021 19:53:30 +0300 Subject: [PATCH 2/2] Add more tests for ClassVar and Final usage --- test-data/unit/check-final.test | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test-data/unit/check-final.test b/test-data/unit/check-final.test index 20c0591bb1356..063b2b8aba886 100644 --- a/test-data/unit/check-final.test +++ b/test-data/unit/check-final.test @@ -1088,4 +1088,6 @@ from typing import Final, ClassVar class A: a: Final[ClassVar[int]] # E: Variable should not be annotated with both ClassVar and Final + b: ClassVar[Final[int]] # E: Final can be only used as an outermost qualifier in a variable annotation + c: ClassVar[Final] = 1 # E: Final can be only used as an outermost qualifier in a variable annotation [out] \ No newline at end of file