pythonoopabstract-classduck-typingbuilt-in-types

Abstract class Container - Python


I am trying to understand why any class that has the __contains__ method becomes an instance of the Container abstract class. I am getting a little confused because the correct way should be like this class dumb(Container): and define your own __contains__ method.

It supposes to be because of duck typing but where is the duck typing there?


Solution

  • Classes are able to customize isinstance checks by implementing __subclasshook__. Many classes will choose to look at properties of the instance to determine the type rather than relying on the inheritance hierarchies

    For example, this is how Container is implemented

    class Container(metaclass=ABCMeta):
    
        __slots__ = ()
    
        @abstractmethod
        def __contains__(self, x):
            return False
    
        @classmethod
        def __subclasshook__(cls, C):
            if cls is Container:
                return _check_methods(C, "__contains__")
            return NotImplemented
    
        __class_getitem__ = classmethod(GenericAlias) ```