user7089560 user7089560 - 4 months ago 20
Python Question

Don't know why this code works (use alternative dictionary class with __missing__ method)

this question arises when i read the book "Python cookbook" by David Beazley, Brian K. Jones, in page 61, 62. I summarize:

>>> s = '{name} has {n} messages.'
>>> name = 'Guido'
>>> n = 37

Now, if just want to replace {name}, but don't want to replace {n}, define an alternative dictionary class with a

>>> class safesub(dict):
def __missing__(self, key):
return '{' + key + '}'


>>> del n # Make sure n is undefined
>>> s.format_map(safesub(vars()))

you get the desired result:

'Guido has {n} messages.'

my question:
why need
method to make this code work?


format_map() will look in its argument for the key 'n'. Because this key is missing, it would raise a KeyError in a normal dict. Defining the __missing__ method determines what happens here instead: '{n}' is returned so that the formatted string remains the same.