Understanding MappingView ABC

948 views Asked by At

What is the difference between a MappingView container and a Sized container? Any examples on how to implement a MappingView container?

I might be misunderstanding ABCs and the docs entirely, but a MappingView container is any container that inherits from Sized, right? If so, then why doesn't my dummy example work?

import collections

class MySized:
    def __len__():
        pass

class MyMappingView(MySized):
    pass

print(issubclass(MySized, collections.Sized)) # True
print(issubclass(MyMappingView, collections.MappingView)) # False
1

There are 1 answers

0
Dimitris Fasarakis Hilliard On

Because you don't subclass from it (virtually or otherwise). MappingView is used as a base class for the keys/items/values views. Sized is used for any object for which getting its size (len) makes sense.

These ABCs are used to check if certain objects in Python follow the interface they define. Instead of creating a custom MappingView you can just register any new classes that conform to it.

Suffice to say, you wouldn't register a class to MappingView since it used solely as a base class to provide a default __len__, __repr__ and __init__ to Keys/Values/Items views. If you have defined a new mapping type that returns custom views, simply register these views to the appropriate Keys/Values/Items views.