[getopt-sig] Re: Prefer non-imperative -- my 1 cent + Change

Derek Harland derek@chocolate-fish.com
Wed, 13 Feb 2002 01:42:03 -0000


Russ Cox rsc@plan9.bell-labs.com wrote
> Can you give an example (perhaps a big one) where option
> parsing with Optik-style objects makes things clearer
> than the traditional loop?

In a loop framework it often seems that flags end up being kept to decide
what to do when another option is met ... perhaps your action when you see B
depends on if A was true ... maybe you need to defer action until you see
both.

In the object orientated world that may look easier.  Well, *I* think it
looks easier.
Ok, well I dont know Optik so I'll answer this from the point of view of my
option parsing module (named, inspiringly, option and posted earlier, sorry
no web source currently).  I expect Optik to be roughly similar

Assuming they are just straight boolean options you would go say

optA, optB = Option('a'), Option('b')
Parser([optA, optB]).parse()

if optA and optB: functionForA_and_B()
elif optA: onlyA()
else: onlyB()

In a loop wouldnt you have to defer your choice until all the arguments are
parsed ... which makes the loop just a "oh its an A, lets set an A flag
somewhere" ?

> All that aside, my big problem with the Optik-style
> modules, and to a lesser extent getopt, is the barrier

Frankly, I find getopt itself quite opaque.

> to entry.  Option parsing is something everyone has to
> do, more or less; it should require as little work
> as possible to get simple parsing in place.  The fact
> that it's _not_ simple enough is why people settle for
> quick and dirty things like
>
>  if sys.argv[1]=='-d':
>   debug=1
>   sys.argv = sys.argv[1:]
>
> when they want just one or two options.  This problem
> is certainly endemic in C programs; I haven't surveyed
> enough Python programs to make informed comments about
> how widespread the practice is in Python.

Its widespread ;-)

> On the other hand, since (in the module I posted)
> it's hardly any more code to use the option parser:
>
>  opt = OptionParser()
>  for o in opt:
>   if o=='-d':
>    debug=1

Again from the point of view of my option module

optDebug = Option('d', 'debug')
Parser([optDebug]).parse()

Thats two lines not four.  Plus you get automatic help options installed.
Plus if they pass you a -c it will complain and say its an invalid option
and dump help.  Plus if you want to know if debug has been set then you can
just test it ... eg

if optDebug: print "Debug info here"

Is it as easy in terms of entry level? No, but I think thats solely because
of the name of Parser() which is a scary term.

> Of course, it's possible that there is some hybrid scheme
> that would satisfy everyone, but I really don't have
> any feel for argument parsing so hairy that you need
> parsing objects and callbacks and the like: someone please
> enlighten me.

I'm not sure if this brings you any closer to Buddha ?

Des.