Description
Without type annotation, implementation of overloaded functions would assume all arguments are of type Any
, and so will fail to properly type check the body (that's assuming one has --checked-untyped-defs
flag on - otherwise, the body is ignored completely).
But annotating the implementation of the overloaded function is annoying:
T = TypeVar('T')
class MyList(Generic[T]):
items: List[T]
@overload
def __getitem__(self, index: int) -> T:
pass
@overload
def __getitem__(self, index: slice) -> Sequence[T]:
pass
def __getitem__(self, index: Union[int, slice]) -> Union[T, Sequence[T]]:
if isinstance(index, int):
... # Return a T here
elif isinstance(index, slice):
... # Return a sequence of Ts here
else:
assert False
In addition, even with this annotation, precise type checking is impossible. For example, if the code returns a T
instead of Sequence[T]
by mistake when index
is a slice
, it will pass type check.
I think mypy should automatically type check the implementation several times, once for each of the possible overloaded variants, and each time assume the argument and return types as provided in that variant. It should also prohibit manual type annotation of implementation of overloaded functions to avoid since it would then be worse than redundant.
Activity
sixolet commentedon Apr 12, 2017
Unfortunately, we can't cover situations where the implementation takes in
(*args, **kwargs)
in this manner at all -- it's too dynamic. And that's not completely uncommon.gvanrossum commentedon Apr 12, 2017
I think we should close this until we have more experience here.
pkch commentedon Apr 12, 2017
@sixolet Nothing is lost in the case of
*args, **kwargs
: currently any type checking mypy does with overloaded implementation assumes all arguments areAny
.gvanrossum commentedon Apr 12, 2017
We considered this and decided against it. There would be too many special cases to consider (e.g. overloading on different arg counts).
Differentiate overload stubs and implementations
cc: Add typing to overloaded function implementations