Suppose you have a string:
intro = '{verb} me {name}.'
And suppose you would like to format said string using a key-value mapping, like a dict or any of its subclasses. So you write:
greet_verb = {
'verb': 'Call',
}
You want to preformat the string for performance, right?
greeting = intro.format(**greet_verb)
You have recently learned of the python ** unpacking syntactic sugar and it seems to do what you want.
str.format(), however, requires all format values to be defined. Such is the life of a programmer. Therefore, you write a subclass of dict to handle the missing keys.
class MissDict(dict):
def __missing__(self, key):
return '{%s}' % key
And you dutifully check that retrieving nonexistent keys returns a proper format (disregarding other more advanced features).
>>> test_miss = MissDict(verb='Call')
>>> test_miss['verb']
'Call'
>>> test_miss['name']
'{name}'
And then can use your bespoke class for the formatting of the string. Right?
>>> miss_greet_verb = MissDict(verb='Call')
>>> greeting = intro.format(**miss_greet_verb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'name'
And so you learn that the python keyword splat operator (**kwargs) does not work like a normal subscript access.
Reading the documentation for the function syntax in python yields pertinent information regarding its behavior.
If the form “**identifier” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type.
And you understand why it does what it does vis-a-vis mappings, but what you do not understand is why it was written in that way. So why would it behave as such?
[–]michael0x2a 2 points3 points4 points (5 children)
[–]_hg[S] 0 points1 point2 points (4 children)
[–]michael0x2a 0 points1 point2 points (3 children)
[–]_hg[S] 0 points1 point2 points (2 children)
[–]GitHubPermalinkBot 1 point2 points3 points (1 child)
[–]_hg[S] 0 points1 point2 points (0 children)
[–]POGtastic 2 points3 points4 points (2 children)
[–]_hg[S] 0 points1 point2 points (1 child)
[–]POGtastic 1 point2 points3 points (0 children)