Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Python mapping?

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?

like image 858
Roméo Després Avatar asked Feb 19 '26 04:02

Roméo Després


2 Answers

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'}
like image 147
khelwood Avatar answered Feb 21 '26 16:02

khelwood


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.

like image 30
vurmux Avatar answered Feb 21 '26 17:02

vurmux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!