Protocol restriction in generics do not work in methods. But work on functions.
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Protocol restriction in generics do not work in methods. But work on functions.
To Reproduce
from typing import *
CanCompare = TypeVar("CanCompare", bound='Comparable')
class Comparable(Protocol):
def __lt__(self: CanCompare, other: CanCompare) -> bool:
pass
def __gt__(self: CanCompare, other: CanCompare) -> bool:
pass
def __le__(self: CanCompare, other: CanCompare) -> bool:
pass
def __ge__(self: CanCompare, other: CanCompare) -> bool:
pass
A = TypeVar('A', covariant=True)
class CustomList(list, Generic[A]):
def getMax(self: 'CustomList'[CanCompare]) -> Optional[CanCompare]:
return functionGetMax(self)
def functionGetMax(aList: 'CustomList'[CanCompare]) -> Optional[CanCompare]:
pass
canCompareMe: CustomList[int] = CustomList([1, 2, 3])
canCompareMe.getMax() # ok
functionGetMax(canCompareMe) # ok
class NotComparable:
pass # no comparisons implemented
impossibleToCompare: CustomList[NotComparable] = CustomList([NotComparable(), NotComparable()])
impossibleToCompare.getMax() # Bug: No error raised
functionGetMax(impossibleToCompare) # Correctly raised error: Value of type variable "CanCompare" of "functionGetMax" cannot be "NotComparable"
Expected Behaviou
Mypy should raise an error on the .getMax() method when called on a CustomList[NotComparable].
Actual Behavior
Instead, no error was raised.
Curiously, the functionGetMax function correctly raises the error.
(Write what happened.)
Your Environment
- Mypy version used: Both mypy 0.910 and mypy-0.920+dev.58fb493b04c61f6202ac8ba0811d3ff8546a8e60
- Mypy command-line flags: No flags
- Mypy configuration options from
mypy.ini(and other config files): no config options - Python version used: Python 3.9.6 (v3.9.6:db3ff76da1, Jun 28 2021, 11:49:53)
- Operating system and version: Macosx 10.15.7
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the supplied reproducer and compare how mypy checks the generic protocol restriction in getMax versus functionGetMax. Trace the method-call type-checking path and its handling of CustomList[NotComparable]; done means the method call produces the same type-variable error as the function call.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100