Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - extra keyword(?) and inheritance

typing.py (from Python 3.6.6 as bundled with Anaconda) declares List class as follows:

class List(list, MutableSequence[T], extra=list):

As far as my understanding goes, it means that List class inherits from list and MutableSequence[T]). What is the meaning of extra assignment in the inheritance list?

like image 612
lukeg Avatar asked Jan 22 '19 01:01

lukeg


1 Answers

In typing.py class GenericMeta takes the extra keyword argument. The extra argument is simply one of the arguments that GenericMeta takes for internal bookeeping. The updates happen here in the __new__ of GenericMeta:

namespace.update({'__origin__': origin, '__extra__': extra,
                      '_gorg': None if not origin else origin._gorg})

From this point on cls.__extra__ becomes part of Typing's internal API, much like __getattr__ or __len__. From the source code, it looks like __extra__ is used to help set attributes for the class that it's passed into:

def __init__(self, *args, **kwargs):
    super(GenericMeta, self).__init__(*args, **kwargs)
    if isinstance(self.__extra__, abc.ABCMeta):
        self._abc_registry = self.__extra__._abc_registry
        self._abc_cache = self.__extra__._abc_cache
    elif self.__origin__ is not None:
        self._abc_registry = self.__origin__._abc_registry
        self._abc_cache = self.__origin__._abc_cache

This code uses __extra__ to set _abc_registry and _abc_cache

like image 143
Primusa Avatar answered Sep 23 '22 10:09

Primusa