[issue9334] argparse does not accept options taking arguments beginning with dash (regression from optparse)

Anders Kaseorg report at bugs.python.org
Fri Jul 23 19:39:22 CEST 2010


Anders Kaseorg <andersk at mit.edu> added the comment:

> Note that the negative number heuristic you're complaining about
> doesn't actually affect your code below.

Yes it does:

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='a2x')
>>> parser.add_argument('--asciidoc-opts',
...     action='store', dest='asciidoc_opts', default='',
...     metavar='ASCIIDOC_OPTS', help='asciidoc options')
>>> parser.parse_args(['--asciidoc-opts', '-1'])
Namespace(asciidoc_opts='-1')
>>> parser.parse_args(['--asciidoc-opts', '-one'])
usage: a2x [-h] [--asciidoc-opts ASCIIDOC_OPTS]
a2x: error: argument --asciidoc-opts: expected one argument

> Your problem is that you want "--safe" to be treated as a positional
> argument even though you've declared it as an option.

No, it doesn’t matter whether --safe was declared as an option: argparse rejected it on the basis of beginning with a dash (as I demonstrated in my small test case, which did not declare --safe as an option, and again in the example above with -one).

> Either the user wants a conf file named "--safe", or the user
> accidentally forgot to type the name of the conf file.

But it’s not argparse’s job to decide that the valid option I passed was actually a typo for something invalid.  This would be like Python rejecting the valid call
  shell = "bash"
  p = subprocess.Popen(shell)
just because shell happens to also be a valid keyword argument for the Popen constructor and I might have forgotten to specify its value.

Including these special heuristics by default, that (1) are different from the standard behavior of all other option parsing libraries and (2) interfere with the ability to pass certain valid options, only leads to strange inconsistencies between command line programs written in different languages, and ultimately makes the command line harder to use for everyone.  The default behavior should be the standard one.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9334>
_______________________________________


More information about the Python-bugs-list mailing list