user7089560 user7089560 - 2 years ago 106
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

>>> 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download