python / python/cpython

Subtle pattern in the __subclasshook__ docs isn't explained

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

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

docs
主要言語
Python
スター
77.2k
フォーク
36k
PR マージ指標
PR 指標を取得中

説明

Documentation

The docs for subclasshook[0] contains the following example:

from abc import ABC

class MyIterable(ABC):
    ...
    @classmethod
    def __subclasshook__(cls, C):
        if cls is MyIterable:
            if any("__iter__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

The docs state that "This method should return True, False or NotImplemented" but the example given only returns True | NotImplemented. This makes it hard for the user to understand how to use the method themselves.

In particular it's not clear to the reader:

  1. Why they may want to return NotImplemented instead of False (this is a common pattern used in stdlib ABCs).
  2. That returning False in __subclasshook__ will override the registration of a class due to the issubclass algorithm. [1][2]

[0] https://docs.python.org/3.12/library/abc.html#abc.ABCMeta.__subclasshook__
[1] Demonstration of this:

from abc import ABC

class Iterable(ABC):
    
    @classmethod
    def __subclasshook__(cls, subclass):
        return hasattr(subclass, "__iter__")

class NotIterable:
    """Does not define __iter__."""


Iterable.register(NotIterable)
assert issubclass(NotIterable, Iterable)
# 'AssertionErrror'

[2] My understanding of the issubclass algorithm is described in this comment: https://github.com/python/cpython/issues/61035#issuecomment-1361180346

Linked PRs
  • gh-100453
  • gh-100503

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

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

はじめの一歩

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

調査の方向性

issue でリンクされている abc.ABCMeta.subclasshook のドキュメントから始め、参照されている issubclass の議論を確認してください。既存の例を True、False、NotImplemented の記載された動作と比較し、そのうえで説明を更新し、違いが明確になるように例を追加または修正してください。開始する前に、リンクされている PR gh-100453 と gh-100503 を確認してください。

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

評価

技術スタック
python
領域
documentation
issue の種類
ドキュメント
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
25/100

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

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