[Python-Dev] potential argparse problem: bad mix of parse_known_args and prefix matching

Eli Bendersky eliben at gmail.com
Wed Nov 27 15:35:13 CET 2013


On Tue, Nov 26, 2013 at 9:30 AM, Eli Bendersky <eliben at gmail.com> wrote:

> Hello,
>
> argparse does prefix matching as long as there are no conflicts. For
> example:
>
> argparser = argparse.ArgumentParser()
> argparser.add_argument('--sync-foo', action='store_true')
> args = argparser.parse_args()
>
> If I pass "--sync" to this script, it recognizes it as "--sync-foo". This
> behavior is quite surprising although I can see the motivation for it. At
> the very least it should be much more explicitly documented (AFAICS it's
> barely mentioned in the docs).
>
> If there's another argument registered, say "--sync-bar" the above will
> fail due to a conflict.
>
> Now comes the nasty part. When using "parse_known_args" instead of
> "parse_args", the above happens too - --sync is recognized for --sync-foo
> and captured by the parser. But this is wrong! The whole idea of
> parse_known_args is to parse the known args, leaving unknowns alone. This
> prefix matching harms more than it helps here because maybe the program
> we're actually acting as a front-end for (and hence using parse_known_args)
> knows about --sync and wants to get it.
>
> Unless I'm missing something, this is a bug. But I'm also not sure whether
> we can do anything about it at this point, as existing code *may* be
> relying on it. The right thing to do would be to disable this prefix
> matching when parse_known_args is called.
>
> Again, at the very least this should be documented (for parse_known_args
> not less than a warning box, IMHO).
>

I created http://bugs.python.org/issue19814 for the documentation patch.

http://bugs.python.org/issue14910 deals with making prefix matching
optional, but that will have to be deferred to 3.5

Eli
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20131127/63f557ab/attachment.html>


More information about the Python-Dev mailing list