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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With