Skip to content

Commit 11a8027

Browse files
Fix false positive in Final local scope variable
1 parent 77cfb98 commit 11a8027

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

mypy/semanal.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3505,7 +3505,8 @@ def unwrap_final(self, s: AssignmentStmt) -> bool:
35053505
if self.loop_depth[-1] > 0:
35063506
self.fail("Cannot use Final inside a loop", s)
35073507
if self.type and self.type.is_protocol:
3508-
self.msg.protocol_members_cant_be_final(s)
3508+
if self.is_class_scope():
3509+
self.msg.protocol_members_cant_be_final(s)
35093510
if (
35103511
isinstance(s.rvalue, TempNode)
35113512
and s.rvalue.no_rhs

test-data/unit/check-final.test

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,37 @@ class P(Protocol):
301301
pass
302302
[out]
303303

304+
[case testFinalInProtocol]
305+
from typing import Protocol, Final, final, ClassVar
306+
307+
class P(Protocol):
308+
var1 : Final[int] = 0 # E: Protocol member cannot be final
309+
310+
@final # E: Protocol member cannot be final
311+
def meth1(self) -> None:
312+
var2: Final = 0
313+
314+
def meth2(self) -> None:
315+
var3: Final = 0
316+
317+
[out]
318+
319+
[case testFinalWithClassVarInProtocol]
320+
from typing import Protocol, Final, final, ClassVar
321+
322+
class P(Protocol):
323+
var1 : Final[ClassVar[int]] = 0 # E: Variable should not be annotated with both ClassVar and Final
324+
var2: ClassVar[int] = 1
325+
326+
@final # E: Protocol member cannot be final
327+
def meth1(self) -> None:
328+
...
329+
330+
def meth2(self) -> None:
331+
var3: Final[ClassVar[int]] = 0 # E: Variable should not be annotated with both ClassVar and Final # E: ClassVar can only be used for assignments in class body
332+
333+
[out]
334+
304335
[case testFinalNotInLoops]
305336
from typing import Final
306337

0 commit comments

Comments
 (0)