feedback on function introspection in argparse

Yuv ubershmekel at
Sat Nov 7 23:45:31 CET 2009

This was posted to the argparse mailing list by Steven Bethard and now
we'd like some feedback from comp.lang.python.

We now have a branch[5] of argparse that supports an ````
function[6] which does
some function introspection to build a command line parser from a
function definition:

------------------------------ ------------------------------
import argparse

def func(foo, bar, baz):
   """A function that foo's a bar with a baz.
   foo - The foo
   bar - The bar to be foo'd
   baz - The baz with which to foo.
   print foo, bar, baz

if __name__ == '__main__':
------------------------------ cmdline ------------------------------
$ -h
usage: [-h] foo bar baz

A function that foo's a bar with a baz.

positional arguments:
 foo         The foo
 bar         The bar to be foo'd
 baz         The baz with which to foo.

optional arguments:
 -h, --help  show this help message and exit

I'd love to hear some feedback on this. At the moment, the code can
introspect argument names, types from defaults, types from annotations
(in Python 3), help messages from docstrings, and knows how to convert
multiple functions into subcommands. The code's compatible and tested
on python 2.3 - 3.1. There are probably more things we could support
[7], but I'd like to get some feedback on what we have so
far. Some specific questions:

* Do you think this is worth including in argparse?
* Would you use the current ```` API in your own code?
* If you wouldn't use it as-is, what additional features/modifications
would you require?

--Steve and Yuv

PS: The authors of pyopt[1], opster[2], optfunc[3] and simpleopt[4]
were CC'd, in the hopes that we can converge to a common API, but they
didn't reply other than the pyopt guy (me) who wrote the patch.
[0] SVN branch at:
[6] The branch also adds ``ArgumentParser.add_function_arguments``
which ```` is built on top of. This method allows you to
match function based arguments with other arguments as necessary,
   def items(n=10):
       return range(n)

   parser = argparse.ArgumentParser()
   args = parser.parse_args()
   with open(args.output_file, 'w') as output_file:
       for item in args.items():
           output_file.write("%d\n" % item)

[7] I can imagine allowing the introspected values to be overridden
with decorators, though it may be out of the scope of this patch.
       listen=optional('-l', default='localhost', help='ip to listen
       port=optional('-p', default=8000, help='port to listen on'),
   def func(dirname, listen='localhost', port=8000, ...):

More information about the Python-list mailing list