python / python/cpython

Subtle pattern in the __subclasshook__ docs isn't explained

Aperta
#100,407 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

docs
Lingua principale
Python
Stelle
77.2k
Fork
36k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia dalla documentazione di abc.ABCMeta.subclasshook collegata nell'issue e esamina la discussione referenziata su issubclass. Confronta l'esempio esistente con il comportamento indicato di True, False e NotImplemented, quindi aggiorna la spiegazione e aggiungi o rivedi gli esempi in modo che la distinzione sia chiara. Controlla le PR collegate gh-100453 e gh-100503 prima di iniziare.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.