5

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?

Roméo Després
  • 1,777
  • 2
  • 15
  • 30

2 Answers2

8

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 Mapping or MutableMapping abstract base classes. Examples include dict, collections.defaultdict, collections.OrderedDict and collections.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'}
khelwood
  • 55,782
  • 14
  • 81
  • 108
6

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.

Community
  • 1
  • 1
vurmux
  • 9,420
  • 3
  • 25
  • 45