Pyrefly misses variance error in mutable generic protocol (false negative)
Describe the Bug
Pyrefly doesn’t report an error when a Protocol uses a covariant type variable in a mutable position. Other type checkers like mypy, andzuban correctly flag this as unsafe because mutable protocols should be invariant. This can potentially lead to incorrect type acceptance.
Code to reproduce:
from typing import Protocol, TypeVar, Generic
T_co = TypeVar('T_co', covariant=True)
T_contra = TypeVar('T_contra', contravariant=True)
class Container(Protocol[T_co]):
item: T_co
def get_item(self) -> T_co: ...
def set_item(self, item: T_co) -> None: ...
class StringContainer:
def __init__(self) -> None:
self.item: str = "hello"
def get_item(self) -> str:
return self.item
def set_item(self, item: str) -> None:
self.item = item
def use_container(container: Container[object]) -> None:
container.set_item(42) # Expected error this line -> false negative
Version
I have used the latest version of pyrefly:
- pyrefly 0.38.0
Sandbox Link
Thanks for the report! You're right that Pyrefly does not implement this currently. @grievejia had some work-in-progress to implement this, so I'm going to make him the owner in case he wants to revive his work to close this.
A few notes:
- We realized that neither mypy nor pyright check for correct typevar use in classes, which we found surprising. To match mypy/pyright behavior, we should only check on protocols, it seems.
- We should error at the definition site, not at the use, as both mypy and pyright do. Curiously, both error on the class and on the invalid setter, but neither error on the invalid attribute (which is read+write).
This issue has someone assigned, but has not had recent activity for more than 2 weeks.
If you are still working on this issue, please add a comment so everyone knows. Otherwise, please unassign yourself and allow someone else to take over.
Thank you for your contributions!
We now error on the definition site of Container.set_item
https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0AFag1wBjXFAA0dACrMYANVSVpAcRjoYlCKIA66fTID64ugF5Z8pZQAUAcmPi708QDdlEDAzMzKAVxgASkMTXHQGSlRzS2JFZXtHMIjUZzpxcMj3bS8ffyD9fVEoVDg4OgBhJNRWLRshXBFxKABtRIBdQMR9Oh7OBhgaRFlQnu7esZ7MGDA6NhgGIwh%2Bmhs4GCgwQLoAWgA%2BYfEhwmOJuimZtYWlgdX1sGlrwYPcLb26ADkwmCPj0YN0IolMoAZQirDYlXC1U0lC66F6Z2mdCMi3QSxRtw2r32n00cIRCLWG0IjyGcAi0V0IAAFusoLgqadTudZvNFstMZsdvtybDTgjKPM-JR4USwCTlkz4b0WZd2TcxQ9lmSItiPl98QSemKJQNoo8ClgkX41qEoTVbOkGNCtENIdaLc1cNgAFYwUQMDrc9V405Wm2UQhyx42AAsACYtnQAMR0ACi%2BFiHpgmDoWmolEY1IgZSgNW9YFQUDWdE0bFQDAgrhgdBAkhAZEFYCgpEIIhoUAosYEpCbLboaCweHwaTCkDYworEDChH0seBMBr1IYDGIcEQAHoN43pi3CLw2BuNBvMGI4Bv0uPJ5Wwhu6GBeHRUO5oKhsLBR%2Bgr5Eb-DcMRfzgWd0DIBhqTCbZq0oOBp3hCwqQAZkIABGcNGXQZp014OA2n0Pw0W4Xh%2BkwbZMAgQUPSrGsLDsCA2HQXgYDsfQGIYbZBQARz8ciU22ABrGBSG2VBRFEeAyhogB3ZR0GY9AQAAX3rETK2rAAxaAYAoQccAIEhyAUoA