python / python/cpython

Subtle pattern in the __subclasshook__ docs isn't explained

Offen
#100,407 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

docs
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
36k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit der in der Issue verlinkten Dokumentation zu abc.ABCMeta.subclasshook und prüfe die referenzierte issubclass-Diskussion. Vergleiche das bestehende Beispiel mit dem beschriebenen Verhalten von True, False und NotImplemented und aktualisiere anschließend die Erklärung und füge Beispiele hinzu oder überarbeite sie, sodass der Unterschied klar ist. Prüfe die verlinkten PRs gh-100453 und gh-100503, bevor du beginnst.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
documentation
Issue-Typ
Dokumentation
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.