In Python, the list
class seems to be a subclass of collections.abc.Sequence
(which makes totally sense):
from collections.abc import Sequence
issubclass(list, Sequence)
# returns True
But the list type doesn't seem to inherit from Sequence
:
dict.__mro__
# returns (dict, object)
So, how does this issubclass(list, Sequence)
is working? How does it return True
?
The 'abc' module in Python library provides the infrastructure for defining custom abstract base classes. 'abc' works by marking methods of the base class as abstract. This is done by @absttractmethod decorator.
Python programming language has four collection data types- list, tuple, sets and dictionary.
In Python, abstract base classes provide a blueprint for concrete classes. They don't contain implementation. Instead, they provide an interface and make sure that derived concrete classes are properly implemented. Abstract base classes cannot be instantiated.
To define an abstract method we use the @abstractmethod decorator of the abc module. It tells Python that the declared method is abstract and should be overridden in the child classes.
The collections.abc
types overload the isinstance()
and issubclass()
operators to check if the object has the expected interface, without requiring true subclassing. See PEP 3119 which introduced abstract base classes; in particular the section on overloading those two functions for more. This is sort of the point of the collections.abc
module. For example, if you define your own class that provides the expected attributes, Python will say that it is an instance/subclass of that type:
>>> class MyClass:
... __contains__ = 0
...
>>> from collections import abc
>>> issubclass(MyClass, abc.Container)
True
The point of checking if something is a subclass or instance of some other type generally is to check that it has the expected interface. In this case, MyClass
does have a __contains__
attribute, so it's assumed to conform to the interface. Of course in this example it doesn't actually conform to the interface: MyClass.__contains__
is not a method, so your program will fail if you try to use a MyClass()
object as a container. However, issubclass()
and isinstance()
will tell you that it is a container object. The usual duck-typing rules apply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With