Skip to content

Use positional only arguments for dunder methods in collections.abc #14071

Open
@randolf-scholz

Description

@randolf-scholz

Currently, some dunder methods like Sequence.__getitem__ do not use positional-only arguments, which causes errors when trying to subclass with positional-only arguments. Therefore, dunder methods, especially operators like __getitem__, that are typically not called using keyword arguments, should probably be annotated using positional only arguments in the stubs.

Code sample in pyright playground

from typing import Protocol, Self, overload, Literal

class SupportsSequenceGetitemA[T](Protocol):
    @overload
    def __getitem__(self, index: int) -> T: ...
    @overload
    def __getitem__(self, index: slice) -> "SupportsSequenceGetitemA[T]": ...

class MySequenceA[T](SupportsSequenceGetitemA[T], Protocol):
    @overload
    def __getitem__(self, index: int, /) -> T: ...
    @overload
    def __getitem__(self, index: slice, /) -> Self: ...  # ❌

class SupportsSequenceGetitemB[T](Protocol):
    @overload
    def __getitem__(self, index: int, /) -> T: ...
    @overload
    def __getitem__(self, index: slice, /) -> "SupportsSequenceGetitemB[T]": ...

class MySequenceB[T](SupportsSequenceGetitemB[T], Protocol):
    @overload
    def __getitem__(self, index: int, /) -> T: ...
    @overload
    def __getitem__(self, index: slice, /) -> Self: ...  # ✅

Metadata

Metadata

Assignees

No one assigned

    Labels

    stubs: improvementImprove/refactor existing annotations, other stubs issues

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions