Skip to content

Create custom type hint for use with multimethod #117

Answered by coady
sylvorg asked this question in Q&A
Discussion options

You must be logged in to vote
  1. The problem is Coll doesn't implement the subclass check correctly.
>>> issubclass(list, Coll)
False
  1. Although there's nothing wrong with using metaclasses, there is a builtin subclass hook which can be easier.
class Coll(abc.ABC):
    @classmethod
    def __subclasshook__(cls, subclass):
        return issubclass(subclass, Iterable) and not issubclass(subclass, (str, bytes, bytearray))

>>> issubclass(list, Coll)
True
>>> issubclass(str, Coll)
False
  1. This may not be necessary, because issubclass(str, Iterable). So if str is being matched, it will take precedence over Iterable anyway.

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@sylvorg
Comment options

Answer selected by coady
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants