Introspecting optparse/argparse objects

Evan Driscoll edriscoll at
Wed Jan 11 21:44:28 EST 2012

On 1/11/2012 19:37, alex23 wrote:
> On Jan 11, 11:26 am, Evan Driscoll <edrisc... at> wrote:
>> (For a concrete idea of a use case, suppose that it did not
>> directly support the --help option and I wanted to write code that took
>> its place.)
> That's a pretty weird definition of 'concrete use case', but anyway...
It's actually closer to the truth than it might seem. I want to feed a
bash-completion-style thing, using the same data structure to both
figure out the possible completions and also do the actual parsing. "Do
the actual parsing" = optparse/argparse, while "figure out the possible
completions" = I need to be able to look at a list.

> If you're wanting to extend the behaviour of the options, won't you
> need to wrap them anyway?
I don't have any need to extend the parsers other than to get the list
of options. (Though now that you've brought that up, perhaps looking at
the _private fields in a subclass would be the best tradeoff? Hmmm.)

> But more to the point, you already have the data: you used it to
> create the options. Why not just keep a handle on that data and refer
> to what you need directly?
But now you're talking about wrapping the parser, because there's no
builtin way (at least that I know of) to store the information in such a
way that you can call the function, because it uses a mix of positional
and keyword arguments. E.g. I can't say just
    args = ('-f', '--foo', help='do foo')
but would have to say something like
    args = ( ('-f', '-foo'), {'help': 'do foo'})
    parser.add_argument(*args[0], *args[1])
or something like that.

I'd want to add some function like 'make_option' which wraps all that
up, and then provide a nicer interface for add_argument, etc., and it
seems like pretty soon I're reimplementing the optparse API. :-) Or at
least it might be that way.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 552 bytes
Desc: OpenPGP digital signature
URL: <>

More information about the Python-list mailing list