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

Brett Cannon brett at python.org
Mon Sep 28 21:22:55 CEST 2009


On Mon, Sep 28, 2009 at 08:49, Steven Bethard <steven.bethard at gmail.com> wrote:
> On Mon, Sep 28, 2009 at 8:27 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On Tue, 29 Sep 2009 12:28:39 am Steven Bethard wrote:
>>> * Would you like argparse to grow an add_getopt_arguments method (as
>>> in my other post)?
>>
>> 0
>>
>>> * If argparse grew an add_getopt_arguments, would you still want to
>>> keep getopt around? And if so, why?
>>
>> Simplicity of the learning curve. Using it is as simple as:
>>
>> getopt.getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
>
> You forgot the for-loop, nested if/else statements and type conversions. ;-)
>

=) I do wonder if people who are advocating for getopt sticking around
realize how much extra code must be written to make sure what it gives
back to you is in some sane manner.

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.

Now, Steven, can you show how best to do this in argparse? 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. I can
only imagine what some newbie might try to do in order to be correct
(if they even try).

-Brett


More information about the Python-Dev mailing list