Closed
Description
I'd like to be able for overload
to handle restrictions on self to the type arguments of a Generic type, but I think mypy ignores restriction on self. Here's an example, where I want to have a different signature for the Lnk.__rshift__
method when the second type argument is a Tuple
:
In = TypeVar('In')
Out = TypeVar('Out')
Other = TypeVar('Other')
_1 = TypeVar('_1')
_2 = TypeVar('_2')
__1 = TypeVar('__1')
__2 = TypeVar('__2')
class Lnk(Generic[In, Out]):
# normal restriction on second argument
@overload
def __rshift__(self, other: 'Lnk[Out, Other]') -> 'Lnk[In,Other]':
pass
# restriction of type argument of self, as I want to have a special case for links to tuples
@overload
def __rshift__(self: 'Lnk[In, Tuple[_1, _2]]',
other: 'Tuple[Lnk[_1, __1], Lnk[_2, __2]]'
) -> 'Lnk[In, Tuple[__1, __2]]':
pass
def __rshift__(self: Any, other: Any) -> Any:
...
# create some links
a: Lnk[str, Tuple[str, int]] = Lnk()
b: Lnk[str, int] = Lnk()
c: Lnk[int, float] = Lnk()
# valid calls to link things together
d: Lnk[str, float] = b >> c
e: Lnk[str, Tuple[int, float]] = a >> (b, c)
# invalid call, but mypy does not check type of self
f: Lnk[str, Tuple[float, int]] = a >> (c, b)
If you create a top level function link
with the exact signatures as __rshift__
, mypy correctly complains about the invalid call, but I'd like to use the operators to create a DSL:
@overload
def link(self: 'Lnk[In, Out]', other: 'Lnk[Out, Other]') -> 'Lnk[In,Other]':
pass
@overload
def link(self: 'Lnk[In, Tuple[_1, _2]]',
other: 'Tuple[Lnk[_1, __1], Lnk[_2, __2]]'
) -> 'Lnk[In, Tuple[__1, __2]]':
pass
def link(self: Any, other: Any) -> Any:
...
# mypy correctly complains
f: Lnk[str, Tuple[float, int]] = link(a, (c, b))
- Python 3.6.5
- mypy 0.620+dev-f5058bcb269a55b33a02c3e3fd345541839bf06e