Covariant subtyping of mutable protocol members is rejected
Mypy rejects this because this is potentially unsafe.Consider this example:
- from typing_extensions import Protocol
- class P(Protocol):
- x: float
- def fun(arg: P) -> None:
- arg.x = 3.14
- class C:
- x = 42
- c = C()
- fun(c) # This is not safe
- c.x << 5 # Since this will fail!
To work around this problem consider whether “mutating” is actually partof a protocol. If not, then one can use a @property
inthe protocol definition:
- from typing_extensions import Protocol
- class P(Protocol):
- @property
- def x(self) -> float:
- pass
- def fun(arg: P) -> None:
- ...
- class C:
- x = 42
- fun(C()) # OK