2

I encounter an example of 'class' when learning about str.format_map() (Python String format_map())

class Coordinate(dict):
    def __missing__(self, key):
        return key

Try arguments:

In [25]: Coordinate(x='6')
Out[25]: {'x': '6'}

In [26]:  Coordinate(x='6', y='7')
Out[26]: {'x': '6', 'y': '7'}

The hard part to understand is that neitherx=6 is a dict nor {'x': '6'} a key.

In official documentation, it specifies:

object.__missing__(self, key) Called by dict.__getitem__() to implement self[key] for dict subclasses when key is not in the dictionary.

It's even more difficult than the previous sample code. There are also good answers here.

dictionary - Python 2 missing method - Stack Overflow

Hidden features of Python - Stack Overflow

The last answer obtain 258 upvotes which frustrates me very much because I get no idea about it. Could it be understood with basic knowledge of python?

Zohnannor
  • 5
  • 2
  • 5

1 Answers1

1

There is nothing to do with __missing__ here:

>>> Coordinate(x='6')
{'x': '6'}
>>> dict(x='6')
{'x': '6'}

This is just calling the dict initializer, because you inherit dict and you don't override __init__.

The effect of defining __missing__ is shown below:

>>> c = Coordinate(x='6')
>>> c['new_key']
'new_key'  # returns the key, instead of raising KeyError
>>> c  # note: does not set it in the dict
{'x': '6'}
wim
  • 338,267
  • 99
  • 616
  • 750
  • Yes, get it.`dict` is parent of class `Coordinate`,not a `parameter` to function `coordinate`. –  Nov 06 '17 at 16:29