Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
randolf-scholz opened this issue May 15, 2025 · 2 comments
Open
Labels
stubs: improvement Improve/refactor existing annotations, other stubs issues

Comments

@randolf-scholz
Copy link
Contributor

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: ...  # ✅
@srittau
Copy link
Collaborator

srittau commented May 15, 2025

While I do agree that these should be positional only, this should be done in CPython first. If the Python maintainers agree that this is a good idea, we can implement it in typeshed – and I'd be okay to do this for all Python versions in typeshed.

@srittau srittau added the stubs: improvement Improve/refactor existing annotations, other stubs issues label May 15, 2025
@Akuli
Copy link
Collaborator

Akuli commented May 15, 2025

This is different with mypy. In mypy, dunder methods are implicitly positional-only, and your example type-checks without errors as is. I'm tempted to say that mypy is correct here, and this is a pyright problem, but I don't feel very strongly about it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: improvement Improve/refactor existing annotations, other stubs issues
Projects
None yet
Development

No branches or pull requests

3 participants