The short answer to your question is: your requirements are contrary to what the module does.
Consider argparse.py:652 (version 1.1; Anaconda3, python 3.7.6)
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
else:
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append('%s %s' % (option_string, args_string))
What you see is the explicitly intended behavior.
I don't see any obvious parameters that would alter this behavior. The only option I see (after, admittedly, 3 minutes of looking) is to create a custom formatter that is exactly like the default one with the offending method (_format_action_invocation
) overridden so that you can do something different than the shipped behavior.
Here's an example of something that at least has the trait of doing what you want. I copied the code from argparse.py and changed the offending code to do what you'd prefer.
import argparse
class CustomFormatter(argparse.HelpFormatter):
def _format_action_invocation(self, action):
if action.option_strings and action.nargs != 0:
# This is the code path that we don't like.
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
return '%s %s' % ('/'.join(action.option_strings), args_string)
# For everything else, use the default behavior.
return super()._format_action_invocation(action)
argParser = argparse.ArgumentParser( formatter_class = CustomFormatter )
argParser.add_argument(
"--operation",
"-o",
action="store",
required=True,
choices=["VIEW","ADD","EDIT","DELETE"],
type=str.upper
)
argParser.parse_args()
Here's the output:
# python soln.py --help
usage: soln.py [-h] --operation {VIEW,ADD,EDIT,DELETE}
optional arguments:
-h, --help show this help message and exit
--operation/-o {VIEW,ADD,EDIT,DELETE}