Q: Callbacks for (what else) Optional Arguments

"Tom Vrankar" <[email protected]> Thu, 14 Apr 2005 12:44:31 -0400
Newsgroups gmane.comp.python.optik.user
Organization Raytheon Systems Portsmouth
Message-ID <425E65AF.14065.342CCA32@localhost>
So I'm trying to use Python's optparse module to handle a complex set 
of options including a couple with optional arguments. I appreciate the 
confusion surrounding how to handle multiple options in the same token, 
but this isn't something that hasn't been solved before: I'll continue 
to support the convention I've learned. For example:

[-a] [-b] [-f [filename]] [args]

Allowed:
-abf fn args
-ab -ffn args
-a -b -f fn args
-f -a args
-abf -- args
-ab -f -- args

Disallowed:
-fab fn args
-fabfb args

So I djinned-up a test case, to help me get used to seeing what I could 
see in a callback, starting from the example of 6.21.4.9. My surprise 
occurred in Optik's handling of tokens like "-ffn". If you start with 
the example code, you can't get at the "fn" argument of the above 
token; it's not in value nor rargs passed to the callback. Why not?

Rooting through optparse.py, I discovered the undocumented significance 
of the "type" keyword to add_option() as used by takes_value(). Without 
this, _process_short_option() leaves the rest of the arg where it is 
rather than insert it at the head of rargs. So I added 'type="str"' to 
add_option(), which triggered the insertion of the remainder of the arg 
into rargs.

I was closer, but this now _always_ required an argument for the "-f" 
switch. I then stumbled onto adding "nargs=0" to avoid popping anything 
from rargs, and that did the trick, allowing my callback to have a shot 
at optionally choosing to consume rargs[0] (the third parameter, value, 
to the callback is now always an empty tuple).

What I'm not sure about is whether _process_short_option() has a subtle 
bug regarding its use with callbacks (should the if with rargs.insert 
and stop=True be independent of takes_value(), at least if 
action="callback"?), or the callback docs need fleshing out...

Or I just plain missed something, as the idiom I now think I need looks 
whacked:

parser.add_option("-c", "--callback", type="str", nargs=0,
                  action="callback", callback=varargs)

Thanks for any other ideas.

Tom Vrankar


-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now.
http://ads.osdn.com/?ad_id=6595&alloc_id=14396&op=click