[Tutor] Help regarding optparse

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Apr 21 00:33:15 CEST 2005

On Wed, 20 Apr 2005, Prasad Kotipalli wrote:

>  I am a newbie to python, I have been working with getopt for parsing
> command line options, but i came to know that optparse module is more
> effecient. Can anyone suggest some ideas why it is powerful than
> getopt.

Hi Prasad,

According to:


the 'declarative' nature of optparse is what makes it nicer to work with
than getopt.

The documentation in optparse shows how to do things like assign value
converters for particular kinds of parameters.  For example, we can say
that we'd like to get an '-n' numeric argument.  In optparse, we'd be able
to declare that by saying:

    parser.add_option("-n", type="int", dest="num")

(taken from http://www.python.org/doc/lib/optparse-store-action.html)

It's "declarative" because we're saying that we expect the '-n' option to
be an int, but we don't really have to say how optparse will do that

We get a lot of stuff for free by letting optparse do the heavy lifint:
if someone tries to put something non-numeric for the '-n' argument,
optparse gives a good error message:

>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option("-n", type="int", dest="num")
<optparse.Option instance at 0x402e556c>
>>> parser.parse_args(args=['-n', 'foobar'])
usage:  [options]

: error: option -n: invalid integer value: 'foobar'

In contrast, if we wanted to provide the same functionality with getopt:


then we could probably do all of that, but it might be more painful, and
would involve manually coding the type tests.

If you have more questions, please feel free to ask.

More information about the Tutor mailing list