Hamy
Hamy

Reputation: 21602

argparse: Include default value and type in '--help'

Right now I'm using this:

parser = argparse.ArgumentParser(description='Run the Foo',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

Which prints out the defaults as so:

--install-only        Do not run benchmark or verification, just install and
                      exit (default: False)

Is there a simple way to have this also print out the types, like this:

--install-only        Do not run benchmark or verification, just install and
                      exit (default: False) (type: Boolean)

Upvotes: 3

Views: 766

Answers (2)

hpaulj
hpaulj

Reputation: 231738

The ArgumentDefaultsHelpFormatter just adds a %(default)s string to all of your argument help lines. You could add that yourself. And you can add a %(type)s string as well.

p=argparse.ArgumentParser()
p.add_argument('--install-only',type=int,help='default %(default)s, type %(type)s')
p.print_help()

producing:

usage: ipython [-h] [--install-only INSTALL_ONLY]

optional arguments:
  -h, --help            show this help message and exit
  --install-only INSTALL_ONLY
                        default None, type int

Keep in mind, though, that type is usually a function like int, float, or None (which is the default 'string' type). There isn't a Boolean type - unless you have written a function that converts a string to a True/False value. For a store_true Action, the type is None.

The action parameter is usually a string, but that gets translated to an Action subclass, not an attribute of the Action itself. Thus %(action)s will not work.

So while it is possible to display the type attribute in the help line, I think it has limited value. You will have greater control by just including that information explicitly in the help string.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249652

You can make your own HelpFormatter class, inspired by the ones included in argparse.py:

class DefaultsAndTypesHelpFormatter(argparse.HelpFormatter):
    def _get_help_string(self, action):
        help = action.help
        if '%(default)' not in action.help:
            if action.default is not argparse.SUPPRESS:
                defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    help += ' (default: %(default)s)'
                if action.type:
                    help += ' (type: %(type)s)'
        return help

This will mostly do what you want, though do note that it doesn't print the type for action='store_true'. I think that's OK, because (default: False) is pretty clear already, but if you want to be even more explicit you can add a clause like if isinstance(action, argparse._StoreTrueAction) and add whatever you like.

Upvotes: 4

Related Questions