Format string unused named arguments

nelsonvarela picture nelsonvarela · Jun 20, 2013 · Viewed 26.2k times · Source

Let's say I have:

action = '{bond}, {james} {bond}'.format(bond='bond', james='james')

this wil output:

'bond, james bond' 

Next we have:

 action = '{bond}, {james} {bond}'.format(bond='bond')

this will output:

KeyError: 'james'

Is there some workaround to prevent this error to happen, something like:

  • if keyrror: ignore, leave it alone (but do parse others)
  • compare format string with available named arguments, if missing then add

Answer

falsetru picture falsetru · Jun 20, 2013

If you are using Python 3.2+, use can use str.format_map().

For bond, bond:

>>> from collections import defaultdict
>>> '{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))
'bond,  bond'

For bond, {james} bond:

>>> class SafeDict(dict):
...     def __missing__(self, key):
...         return '{' + key + '}'
...
>>> '{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))
'bond, {james} bond'

In Python 2.6/2.7

For bond, bond:

>>> from collections import defaultdict
>>> import string
>>> string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond'))
'bond,  bond'

For bond, {james} bond:

>>> from collections import defaultdict
>>> import string
>>>
>>> class SafeDict(dict):
...     def __missing__(self, key):
...         return '{' + key + '}'
...
>>> string.Formatter().vformat('{bond}, {james} {bond}', (), SafeDict(bond='bond'))
'bond, {james} bond'