Say I have a function func and an object obj of class Class. I have the following error:
>>> func(**obj)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() argument after ** must be a mapping, not Class
Hence my question: what is a mapping? Are all mappings subclasses of dict? Or is there a list of methods (e.g. __getitem__, __iter__, ...) that Class has to implement to be considered a mapping?
The term "mapping" is described in the Python glossary as:
A container object that supports arbitrary key lookups and implements the methods specified in the
MappingorMutableMappingabstract base classes. Examples includedict,collections.defaultdict,collections.OrderedDictandcollections.Counter.
The requirements to subclass collections.abc.Mapping are described in its docstring:
A Mapping is a generic container for associating key/value pairs.
This class provides concrete generic implementations of all methods except for
__getitem__,__iter__, and__len__.
So you can define a new mapping type by subclassing collections.abc.Mapping, and implementing three methods: __len__, __getitem__, and __iter__.
>>> from collections.abc import Mapping
>>> def func(**kwargs):
... print(kwargs)
...
>>> class MyMapping(Mapping):
... def __len__(self):
... return 1
... def __getitem__(self, k):
... return 'bananas'
... def __iter__(self):
... return iter(['custard'])
...
>>> func(**MyMapping())
{'custard': 'bananas'}
According to Python docs:
A container object that supports arbitrary key lookups and implements the methods specified in the Mapping or MutableMapping abstract base classes. Examples include:
- dict
- collections.defaultdict
- collections.OrderedDict
- collections.Counter.
The class is a mapping if it implements all methods from the Mapping / MutableMapping.
If you will create a Mapping/MutableMapping derived class and implement all of this, you will get a class that is a mapping.
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