[Python-Dev] PEP 389: argparse - new command line parsing module

"Martin v. Löwis" martin at v.loewis.de
Tue Sep 29 05:44:30 CEST 2009


> Let's take ``getopt.getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])``
> as an example and simply assume that 'alpha' takes a string as an
> argument and that it's required and that 'beta' is a boolean flag. To
> pull everything out you could do::
> 
>   options, args = getopt.getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
>   options_dict = dict(options)
>   alpha = options_dict.get('-a', options_dict.get('--alpha', ''))
>   beta = '-b' in options_dict or '--beta' in options_dict
> 
>   main(alpha, beta, args)
> 
> Obviously if one of the getopt supporters has a better way of doing
> this then please speak up.

As Yuvgoog Greenle says, the canonical getopt way is to write

alpha = None
beta = False
options, args = getopt.getopt(sys.argv[1:],"a:b",['alpha=','beta']):
for opt, val in options:
    if arg in ('-a','--alpha'):
        alpha = val
    elif arg in ('-b','--beta'):
        beta = True
main(alpha, beta, args)

Even though this is many more lines, I prefer it over
optparse/argparse: this code has only a single function call,
whereas the argparse version has three function calls to remember.
The actual processing uses standard Python data structures which
I don't need to look up in the documentation.

> Now, Steven, can you show how best to do this in argparse?

This demonstrates my point: you were able to use getopt right away
(even though not in the traditional way), whereas you need to ask
for help on using argparse properly.

> I am
> willing to bet that the total number of lines to do this is not that
> much more and does not require you to know to use 'or' or the dict
> constructor along with dict.get() in order to keep it compact.

See above - getopt users don't care about compactness in
the processing.

> I can
> only imagine what some newbie might try to do in order to be correct
> (if they even try).

Depends on the background of the newbie. If they come from C, they
immediately recognize the way of doing things.

Regards,
Martin


More information about the Python-Dev mailing list