Python string resolution using dictionaries

Viewed 30

Literally from the argparse built in library from python 3.8.10

def _expand_help(self, action):
    params = dict(vars(action), prog=self._prog)
    for name in list(params):
        if params[name] is SUPPRESS:
            del params[name]
    for name in list(params):
        if hasattr(params[name], '__name__'):
            params[name] = params[name].__name__
    if params.get('choices') is not None:
        choices_str = ', '.join([str(c) for c in params['choices']])
        params['choices'] = choices_str
    return self._get_help_string(action) % params

On the last line of code: "params", a dictionary, is used to update the help of a program to display to the user. This is passed in while defining an option for the argument parser:

parser = argparse.ArgumentParser()
parser.add_argument('--action', help="String I want to output when --help is used as a parameter. show me the default %(default)",
    choices=OPTIONS, default=OPTIONS[0])

I want argparse to to substitute the default option into the help when printed. How do you get python3 to resolve dictionary replacements correctly?

My understanding was that I needed to use a format like the following:

"%(default)" % {"default": "DEFAULT_VALUE", "help": "insert help here", "options": ["option1", "option2", "option3", "DEFAULT_VALUE"]}

However, this doesn't seem to work.

1 Answers

When resolving dictionaries in python using standard string resolution using the '%' operator. The correct syntax is "%(dict_key)" followed by the character usage needed for the resolution. Example:

In [2]: "%(key)s" % {"key": "v"}                                                                                                                                             
Out[2]: 'v'

In [3]: "%(key)s" % {"key": 1}                                                                                                                                               
Out[3]: '1'

In [4]: "%(key)i" % {"key": 1}                                                                                                                                               
Out[4]: '1'

In [5]: "%(key)f" % {"key": 1}                                                                                                                                               
Out[5]: '1.000000'

In [6]: "%(key)x" % {"key": 7}                                                                                                                                               
Out[6]: '7'

In [7]: "%(key)x" % {"key": 13}                                                                                                                                              
Out[7]: 'd'
Related