Skip to content

Implementation of overloaded function should be automatically typed #3160

Closed
@pkch

Description

@pkch

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions