Q: argparse.add_argument()

Chris Angelico rosuav at gmail.com
Sat Mar 18 15:22:33 EDT 2023


On Sun, 19 Mar 2023 at 06:09, Thomas Passin <list1 at tompassin.net> wrote:
>
> On 3/18/2023 2:02 PM, Gisle Vanem via Python-list wrote:
> > I accidentally used 'argparse' like this in my Python 3.9 program:
> >    parser.add_argument ("-c, --clean",  dest="clean", action="store_true")
> >    parser.add_argument ("-n, --dryrun", dest="dryrun", action="store_true")
> >
> > instead of:
> >    parser.add_argument ("-c", "--clean",  dest="clean",
> > action="store_true")
> >    parser.add_argument ("-n", "--dryrun", dest="dryrun",
> > action="store_true")
> >
> > So any use of 'my-prog.py -cn' threw an error:
> >    error: unrecognized arguments: -cn
> >
> > So is there something that throws an error on this wrong use of
> > "-c, --clean" instead? Could be useful. Or is "-c, --clean" legit somehow?
>
>
> Are you trying to troll here?  You just showed how you got an error with
> this construction, so why are you asking how to get an error with this
> construction?
>

There's a small difference in the way that the arguments are passed.
In the accidental example, "-c, --clean" is passed as a single
argument, which is a bug.

The truth is, though, that no program can ever tell you about all of
your bugs. The "-c, --clean" form is technically valid, and will match
an argument that looks exactly like it; I suppose argparse might be
coded to give a warning if there's a space inside an argument, but
that would be extremely annoying to anyone who actually wants it.

Ultimately, the only way to find bugs is to test, and to get good at
noticing expected patterns (for instance, if your editor highlights
strings or quote characters, your brain should expect to see them in
certain places). It's a nice courtesy when a library will help you to
find your own bugs, but there's a limit to what it can do.

ChrisA


More information about the Python-list mailing list