Skip to content

Commit 6a7c7cd

Browse files
authored
Allow class variable as implementation for read only attribute (#14081)
Fixes #10289 Unless I am missing something, this indeed looks safe, so I am going to allow this.
1 parent 7d0d1d9 commit 6a7c7cd

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

mypy/messages.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2663,6 +2663,7 @@ def get_bad_protocol_flags(
26632663
if (
26642664
IS_CLASSVAR in subflags
26652665
and IS_CLASSVAR not in superflags
2666+
and IS_SETTABLE in superflags
26662667
or IS_CLASSVAR in superflags
26672668
and IS_CLASSVAR not in subflags
26682669
or IS_SETTABLE in superflags

mypy/subtypes.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1040,7 +1040,10 @@ def named_type(fullname: str) -> Instance:
10401040
if not is_subtype(supertype, subtype):
10411041
return False
10421042
if not class_obj:
1043-
if (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags):
1043+
if IS_SETTABLE not in superflags:
1044+
if IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags:
1045+
return False
1046+
elif (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags):
10441047
return False
10451048
else:
10461049
if IS_VAR in superflags and IS_CLASSVAR not in subflags:

test-data/unit/check-protocols.test

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1153,6 +1153,25 @@ x2 = y2 # E: Incompatible types in assignment (expression has type "PP", variabl
11531153
# N: Protocol member P.attr expected settable variable, got read-only attribute
11541154
[builtins fixtures/property.pyi]
11551155

1156+
[case testClassVarProtocolImmutable]
1157+
from typing import Protocol, ClassVar
1158+
1159+
class P(Protocol):
1160+
@property
1161+
def x(self) -> int: ...
1162+
1163+
class C:
1164+
x: ClassVar[int]
1165+
1166+
class Bad:
1167+
x: ClassVar[str]
1168+
1169+
x: P = C()
1170+
y: P = Bad() # E: Incompatible types in assignment (expression has type "Bad", variable has type "P") \
1171+
# N: Following member(s) of "Bad" have conflicts: \
1172+
# N: x: expected "int", got "str"
1173+
[builtins fixtures/property.pyi]
1174+
11561175
[case testSettablePropertyInProtocols]
11571176
from typing import Protocol
11581177

0 commit comments

Comments
 (0)