Format string unused named arguments

defaultdict, missing-data, python, string, string-formatting

Solution

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'))

Result:

'bond,  bond'

For `bond, {james} bond`:

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

'{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))

Result:

'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'))

Result:

'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'))

Result:

'bond, {james} bond'

Problem

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

Original source

Related problems