python / python/cpython

Subtle pattern in the __subclasshook__ docs isn't explained

Open
#100,407 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the abc.ABCMeta.subclasshook documentation linked in the issue and review the referenced issubclass discussion. Compare the existing example with the stated behavior of True, False, and NotImplemented, then update the explanation and add or revise examples so the distinction is clear. Check linked PRs gh-100453 and gh-100503 before starting.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.