When I specify a parameter for argparse with both a short and long name, e.g.:
parser.add_argument("-m", "--min", dest="min_value", type=float, help="Minimum value")
and ask for --help
, I get:
-m MIN_VALUE, --min MIN_VALUE
Minimum value
This annoys me. I would like MIN_VALUE
not to be repeated. So, for example:
[-m | --min-value] MIN_VALUE
Minimum value
can I get argparse to print that (other than by overriding the --help
message entirely)?
You don't have to override the help
message, just create your own HelpFormatter
class:
import argparse
class MyFormatter(argparse.HelpFormatter):
def _format_action_invocation(self, action):
if not action.option_strings:
(metavar,) = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
if action.nargs == 0:
parts.extend(action.option_strings)
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
parts.extend([f'[{" | ".join(action.option_strings)}] {args_string}']) # Customize the format here
return " ".join(parts)
# Example usage
parser = argparse.ArgumentParser(formatter_class=MyFormatter)
This way you can adjust the structure of the arguments printed within the help message without having to completely change it.