Skip to content
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

Allow class variable as implementation for read only attribute #14081

Merged
merged 2 commits into from
Nov 16, 2022
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
1 change: 1 addition & 0 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -2658,6 +2658,7 @@ def get_bad_protocol_flags(
if (
IS_CLASSVAR in subflags
and IS_CLASSVAR not in superflags
and IS_SETTABLE in superflags
or IS_CLASSVAR in superflags
and IS_CLASSVAR not in subflags
or IS_SETTABLE in superflags
Expand Down
5 changes: 4 additions & 1 deletion mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1027,7 +1027,10 @@ def named_type(fullname: str) -> Instance:
if not is_subtype(supertype, subtype):
return False
if not class_obj:
if (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags):
if IS_SETTABLE not in superflags:
if IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags:
return False
elif (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags):
return False
else:
if IS_VAR in superflags and IS_CLASSVAR not in subflags:
Expand Down
19 changes: 19 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -1153,6 +1153,25 @@ x2 = y2 # E: Incompatible types in assignment (expression has type "PP", variabl
# N: Protocol member P.attr expected settable variable, got read-only attribute
[builtins fixtures/property.pyi]

[case testClassVarProtocolImmutable]
from typing import Protocol, ClassVar

class P(Protocol):
@property
def x(self) -> int: ...

class C:
x: ClassVar[int]

class Bad:
x: ClassVar[str]

x: P = C()
y: P = Bad() # E: Incompatible types in assignment (expression has type "Bad", variable has type "P") \
# N: Following member(s) of "Bad" have conflicts: \
# N: x: expected "int", got "str"
[builtins fixtures/property.pyi]

[case testSettablePropertyInProtocols]
from typing import Protocol

Expand Down