user7089560 user7089560 - 1 month ago 8
Python Question

(python) don't know why this code work (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
__missing__()
method

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


then

>>> 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
__missing__()
method to make this code work?

Answer

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

Comments