Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the list class a subclass of collections.abc.Sequence in Python?

Tags:

python

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?

like image 346
Phylliade Avatar asked Aug 10 '19 21:08

Phylliade


People also ask

What is the ABC class in Python?

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.

What are the collections in Python?

Python programming language has four collection data types- list, tuple, sets and dictionary.

What is base class in Python?

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.

What is @abstractmethod in Python?

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.


1 Answers

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.

like image 55
alkasm Avatar answered Nov 03 '22 13:11

alkasm