Covariant subtyping of mutable protocol members is rejected

Mypy rejects this because this is potentially unsafe.Consider this example:

  1. from typing_extensions import Protocol
  2.  
  3. class P(Protocol):
  4. x: float
  5.  
  6. def fun(arg: P) -> None:
  7. arg.x = 3.14
  8.  
  9. class C:
  10. x = 42
  11. c = C()
  12. fun(c) # This is not safe
  13. 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:

  1. from typing_extensions import Protocol
  2.  
  3. class P(Protocol):
  4. @property
  5. def x(self) -> float:
  6. pass
  7.  
  8. def fun(arg: P) -> None:
  9. ...
  10.  
  11. class C:
  12. x = 42
  13. fun(C()) # OK