[Python-ideas] Pyopt - an attempt at a pythonic optparse

Nick Coghlan ncoghlan at gmail.com
Mon Sep 7 13:29:52 CEST 2009

Yuvgoog Greenle wrote:
> Just to clarify why I feel getopt/optparse aren't as pythonic - to me
> they feel clunky in that I need alot of ultra-explicit, extra-long lines
> to do some very basic things. The python I'm used to allows me to use
> open('filename').read() with reasonable default parameters. Now that I
> think of it, actually wrapping optparse might have been an easier
> implementation route for some of the functionality...

Something to think about is the possibility of redesigning your API
proposal to function as a convenience wrapper around the existing
optparse implementation. Convenience wrappers have a much lower hurdle
to clear than complete alternative APIs (since the full power of the
original API remains available by dropping back to the lower level).
It's still no guarantee of course - there still needs to be a
python-ideas (and then python-dev) consensus that the proposed wrappers
actually are an improvement.

There are definitely some things about the basic concepts behind your
API that bother me as it currently stands:

1. One of the major features of optparse is that it encourages a data
driven approach to option definition. Going back to a largely procedural
approach as in your examples is not a step forward.

2. The use of a single global parser is a fairly questionable feature.

3. Losing the options object makes it more difficult to pass options
around to code that may only care about some of the options

A potentially valuable addition to optparse might just focus on your
"CmdPos" idea and add the ability to add commands to the option parser:

import optparse

parser = optparse.parser()

def main(options, *args):
  """Command line help info goes here"""
  # Main body goes here

# Adding more than one command would result in the first argument
# being used to select between them by name as with CmdPos

if __name__ == "__main__":

The other thing I find somewhat tedious with optparse is having to do
lots of procedural checking of option constraints in order to provide
helpful error messages. Being able to add independent constraint checks
would help a great deal with that:

def check_args(parser, options, *args):
  if len(args) != 2:
    parser.error("Exactly 2 arguments required")


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list