Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subtle pattern in the __subclasshook__ docs isn't explained #100407

Open
JosephSBoyle opened this issue Dec 21, 2022 · 0 comments
Open

Subtle pattern in the __subclasshook__ docs isn't explained #100407

JosephSBoyle opened this issue Dec 21, 2022 · 0 comments
Labels
docs Documentation in the Doc dir

Comments

@JosephSBoyle
Copy link

JosephSBoyle commented Dec 21, 2022

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: #61035 (comment)

@JosephSBoyle JosephSBoyle added the docs Documentation in the Doc dir label Dec 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Documentation in the Doc dir
Projects
None yet
Development

No branches or pull requests

1 participant