You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Protocol does not accept subtype as class attribute #14963
from typing import Protocol
class Str(str):
pass
class A:
field: Str
class B(Protocol):
field: str
def f(arg: B):
pass
f(A())
and get:
main.py:15: error: Argument 1 to "f" has incompatible type "A"; expected "B" [arg-type]
main.py:15: note: Following member(s) of "A" have conflicts:
main.py:15: note: field: expected "str", got "Str"
Found 1 error in 1 file (checked 1 source file)
Why is subtype not accepted as a class attribute of a protocol? Does this not adhere to the Liskov Substitution Principle?
Please help explain the rationale behind such an implementation or if this is actually a bug.
Activity
JelleZijlstra commentedon Mar 27, 2023
This is because you made a writable attribute. Given a variable
arg: B, it is legal to doarg.field = "x", but that is not compatible with typeA.To make a read-only protocol field, use
@property.AlexWaygood commentedon Mar 27, 2023
See https://mypy.readthedocs.io/en/stable/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected