basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

`tuple` can be subtyped to unsafely override the behavior of `__getitem__`

Open DetachHead opened this issue 4 months ago • 1 comments

Code sample in basedpyright playground

from typing import SupportsIndex, overload, override, reveal_type


class Foo(tuple[int, str]):
    @overload
    def __getitem__(self, item: SupportsIndex, /) -> int: ...
    @overload
    def __getitem__(self, key: slice, /) -> tuple[int, str]: ...

    @override
    def __getitem__(self, item: SupportsIndex | slice, /) -> int | str | tuple[int, str]:
        return super().__getitem__(0)


baz = Foo((1, ""))

qux = baz[1]

reveal_type(qux) # basedpyright: str, runtime: int

DetachHead avatar Oct 25 '25 15:10 DetachHead

maybe we should try and get tuple.__getitem__ marked as @final in typeshed

DetachHead avatar Oct 25 '25 15:10 DetachHead