python / python/cpython

Make abstract/dunder methods positional-only.

オープン
#135,312 コメント 18 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib topic-typing type-feature
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Feature or enhancement

It would be nice if certain abstract methods / dunder methods would be defined with positional-only arguments, so that when one subclasses them an appropriate name can be chosen, or they can be defined positional-only in the subclass.[^1]

Code sample in pyright playground[^1]

from typing import overload
from collections.abc import Sequence

class MySequence[T](Sequence[T]):
    def __len__(self): return 0
    @overload
    def __getitem__(self, idx: int, /) -> T: ...
    @overload
    def __getitem__(self, idx: slice, /) -> Sequence[T]: ...
    def __getitem__(self, idx: int | slice, /) -> T | Sequence[T]:  # ❌ override
        return MySequence[T]()

In some cases, the stubs already fake that the argument is positional-only, such as for Container.__contains__:

Personally, I think only changing the stubs would be a pragmatic choice, but I was told by the maintainers that they believe this change should be done in Cpython first.

Backward Compatibility

  1. Changing non-abstract methods can potentially break user code. For example, this is currently legal code at runtime

    from collections.abc import Container.
    Container.__subclasshook__(C=list)  # True
    
  2. Changing the signature of abstract methods can introduce type-checker errors Code sample in pyright playground[^1]

    from collections.abc import Sequence
    def get(x: Sequence[float], index: int) -> float:
        return x.__getitem__(index=index)
    

With this in mind, I believe changing abstrac dunder methods to use positional only arguments should be relatively safe, as calling them directly with keyword is very uncommon, and at worst it will introduce type errors.

Personally, I'd also like so see methods like Container.__subclasshook__ use positional-only arguments, but I also understand if this is not feasible due to bc-conerns.

[^1]: Note that mypy special cases certain dunder methods, and yields different results than pyright on these examples

Has this already been discussed elsewhere?

https://github.com/python/typeshed/issues/14071

Linked PRs
  • gh-136324

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず Lib/_collections_abc.py と typeshed/stdlib/typing.pyi にある引用された定義から始め、次にリンクされている PR gh-136324 と関連する typeshed issue を確認します。合意された abstract メソッドおよび dunder メソッドのシグネチャが CPython で更新され、文書化された後方互換性に関する懸念に対処できれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
機能追加
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。