Zed Shaw's Proposed ArgParse API

Posted on April 10, 2009

I like ArgParse: it’s a much needed update to the old OptParse. However, I’ve always felt that OptParse was a little wordy and it looks like ArgParse is following that tradition. Apparently Zed Shaw feels the way I do as he proposed a leaner API on Twitter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import argparse

# argparse has lots of typing, if there was just a simple method like:

def build_parser(args):
    parser = argparse.ArgumentParser()

    for arg, kw in args:
        parser.add_argument(arg, **kw)

    return parser, parser.parse_args()


# I could then define my arguments as simple data:

arguments = [
    ('integers',
     {'metavar': 'int', 'type': int, 'choices': xrange(10), 'nargs': '+',
        'help': 'an integer in the range 0..9'}),
    ('--sum',
     {'dest': 'accumulate', 'action': 'store_const', 'const': sum,
        'default': max, 'help': 'sum the integers (default: find the max)'})
]

# and then easily convert them in one shot to the parser and the arguments:
parser, args = build_parser(arguments)

print args.accumulate(args.integers)

It’s definitely a step in the right direction. The build_parser function should be in the API. That way the developer only has to specify the arguments data structure and hand it off with no extra work involved. Great work, Zed.

Although I just had an idea: a docstring mini-language.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def run():
    args = """
        --filename:
            type: string
            dest: fname
            help: the file to analyze
        --somearg:
            type: int
    """
    parser = argparse.ArgumentParser()
    parser.parse_argstring(args)
    ...