Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 579
Hamy Avatar asked May 21 '26 14:05

Hamy


1 Answers

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.

like image 90
John Zwinck Avatar answered May 23 '26 03:05

John Zwinck