Skip to content

Implementation of overloaded function should be automatically typed #3160

Closed

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.

Activity

  1. sixolet commented on Apr 12, 2017

    @sixolet
    Collaborator

    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.

  2. gvanrossum commented on Apr 12, 2017

    @gvanrossum
    Member

    I think we should close this until we have more experience here.

  3. pkch commented on Apr 12, 2017

    @pkch
    ContributorAuthor

    @sixolet Nothing is lost in the case of *args, **kwargs: currently any type checking mypy does with overloaded implementation assumes all arguments are Any.

  4. gvanrossum commented on Apr 12, 2017

    @gvanrossum
    Member

    We considered this and decided against it. There would be too many special cases to consider (e.g. overloading on different arg counts).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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