Search code examples
pythonsliceabstract-base-class

Which built-in abstract base classes support slicing?


The documentation of Python lists all the methods that implementations of abstract base classes should have very clearly at https://docs.python.org/3/library/collections.abc.html. Slicing is however only sometimes implemented as part of __getitem__.

I would imagine all classes inheriting from Sequence would implement it, is that the case? Are there any other ways of knowing that an object supports slicing?

Edit: I also found https://docs.python.org/3/library/stdtypes.html#typesseq-common in the documentation. It lists the methods as 'supported by most sequence types'.
I'll take that as 'Sequence types should implement slicing' and annotate using that.


Solution

  • In typeshed/typing.pyi, Sequence is typed as follows:

    class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]):
        @overload
        @abstractmethod
        def __getitem__(self, i: int) -> _T_co: ...
        @overload
        @abstractmethod
        def __getitem__(self, s: slice) -> Sequence[_T_co]: ...
        ...
    

    https://github.com/python/typeshed/blob/master/stdlib/3/typing.pyi#L274

    Any Sequence type should therefore support slicing. Slices are not indicated for other types in the typing module. A Mapping for example explicitly lists the key type of the mapping.