Python collections.MappingView

abc, collections, python

Solution

`MappingView` is essentially the base class for user defined views. It implements the `Sized` interface by providing the `__len__` attribute which is the length of its `_mapping` member, so if this implementation is fine for you, you do not need to implement your own `__len__`.

It holds common code for `KeysView`, `ItemsView` and `ValuesView`. These last classes can be used wherever a view like `my_dict.keys()`, `my_dict.items()` or `my_dict.values()` would be expected. If you create a new user defined kind of data and want to create a view that can be neither compared to `keys`, `values` or `items`, then you could subclass `MappingView` directly and implement differently the `__contains__` and `__iter__` functions.

Problem

I was checking out the very nice collections library and more specific the Abstract Base Classes (ABC). One I could not get my head around: the MappingView. - What is its use? What is its advantage over Sized? An example perhaps? - Documentation says its base class is Sized, but on the other hand there is a len mixin... So do we have to implement len, or not? For the documentation, see collections

Original source