Skip to content

Ordering matters for @overload #1270

Closed
@mgeisler

Description

@mgeisler

I am trying to model a generic container (a Pandas Series though it shouldn't matter too much for this). The container has a generic "value type" and a generic "index type". When iterating over the container, you get the value type back. So I tried with:

class Series(Generic[VT, IT], Sequence[VT]):

    @overload
    def __getitem__(self, key: slice) -> List[VT]: ...

    @overload
    def __getitem__(self, key: int) -> VT: ...

This gives me an error:

stubs/pandas/__init__.pyi: note: In class "Series":
stubs/pandas/__init__.pyi:186: error: Signature of "__getitem__" incompatible with supertype "Sequence"

That baffled me for a while and on a whim, I tried reordering the two signatures:

class Series(Generic[VT, IT], Sequence[VT]):

    @overload
    def __getitem__(self, key: int) -> VT: ...

    @overload
    def __getitem__(self, key: slice) -> List[VT]: ...

The error is now gone! :-)

When I first got the error, I tried going into typing.py to see exactly what signature Sequence has. That didn't help me since Sequence is defined as

class Sequence(Sized, Iterable[T_co], Container[T_co],
               extra=collections_abc.Sequence):
    pass

I think it could have been helpful if mypy could have written the exact types it was comparing.

This was tested with 0ec0cb4.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions