Skip to content

Return type of slice-aware __getitem__ #902

Closed
@o11c

Description

@o11c

This has been discussed before, but since this involves a language item, it is especially important, and it might be acceptable to special-case a solution.

Since @overload is not allowed in non-stubs, it's not clear how slicing should be implemented in user-defined containers.

In stubs, you can use:

class Foo(Generic[T]):
    @overload
    def __getitem__(self, i: int) -> T: ...
    @overload
    def __getitem__(self, s: slice) -> Foo[T]: ...

But in source files the best you can do is:

class Foo(Generic[T]):
    def __getitem__(self, i: Union[int, slice]) -> Union[T, List[T]]: ...

which will require unacceptable casts at every call site. (incidentally, slice should be a generic, not every use will be int).

And currently, it is difficult to mix some parts from a stub file and some not. I am currently investigating whether CRTP works though.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions