From 12d5da449b54ddeb44e4e582defe354cc70b3e94 Mon Sep 17 00:00:00 2001 From: STerliakov Date: Thu, 30 Oct 2025 23:01:04 +0100 Subject: [PATCH] Do not treat annotated self-assign as special --- mypy/semanal.py | 2 +- test-data/unit/check-final.test | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index d7b50bd09496..0fe0c20d7f63 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -3286,7 +3286,7 @@ def analyze_identity_global_assignment(self, s: AssignmentStmt) -> bool: Return true if special casing was applied. """ - if not isinstance(s.rvalue, NameExpr) or len(s.lvalues) != 1: + if not isinstance(s.rvalue, NameExpr) or len(s.lvalues) != 1 or s.type is not None: # Not of form 'X = X' return False lvalue = s.lvalues[0] diff --git a/test-data/unit/check-final.test b/test-data/unit/check-final.test index e3fc4614fc06..278755fa213c 100644 --- a/test-data/unit/check-final.test +++ b/test-data/unit/check-final.test @@ -1173,6 +1173,19 @@ class MyClass: a: None a: Final[int] = 1 # E: Cannot redefine an existing name as final # E: Name "a" already defined on line 5 +[case testFinalCannotBeRedefinition] +from typing import Final + +# This time travel is suboptimal but good enough for now? +a = 0 # E: Cannot assign to final name "a" +b = 0 # E: Cannot assign to final name "b" + +a: Final = a # E: Cannot redefine an existing name as final +b: Final = 1 # E: Cannot redefine an existing name as final + +a = 1 # E: Cannot assign to final name "a" +b = 1 # E: Cannot assign to final name "b" + [case testFinalOverrideAllowedForPrivate] from typing import Final, final