Skip to content

Fix False positive - Final local scope variable in Protocol #17308

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3505,7 +3505,8 @@ def unwrap_final(self, s: AssignmentStmt) -> bool:
if self.loop_depth[-1] > 0:
self.fail("Cannot use Final inside a loop", s)
if self.type and self.type.is_protocol:
self.msg.protocol_members_cant_be_final(s)
if self.is_class_scope():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(at least as I'm reading it, this is the key change and hence my question about line 1623)

self.msg.protocol_members_cant_be_final(s)
if (
isinstance(s.rvalue, TempNode)
and s.rvalue.no_rhs
Expand Down
44 changes: 44 additions & 0 deletions test-data/unit/check-final.test
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,50 @@ class P(Protocol):
pass
[out]

[case testFinalInProtocol]
from typing import Final, Protocol, final

class P(Protocol):
var1 : Final[int] = 0 # E: Protocol member cannot be final

@final # E: Protocol member cannot be final
def meth1(self) -> None:
var2: Final = 0

def meth2(self) -> None:
var3: Final = 0

def meth3(self) -> None:
class Inner:
var3: Final = 0 # OK

@final
def inner(self) -> None: ...

class Inner:
var3: Final = 0 # OK

@final
def inner(self) -> None: ...

[out]

[case testFinalWithClassVarInProtocol]
from typing import Protocol, Final, final, ClassVar

class P(Protocol):
var1 : Final[ClassVar[int]] = 0 # E: Variable should not be annotated with both ClassVar and Final
var2: ClassVar[int] = 1

@final # E: Protocol member cannot be final
def meth1(self) -> None:
...

def meth2(self) -> None:
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

[out]

[case testFinalNotInLoops]
from typing import Final

Expand Down
Loading