docstringargs: Python module for setting up argparse
rosuav at gmail.com
Mon Apr 20 09:45:58 CEST 2015
On Mon, Apr 20, 2015 at 5:22 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Monday 20 April 2015 16:20, Chris Angelico wrote:
>> Looking for comments, recommendations, advice that I've just wasted
>> half a day on something utterly useless, whatever it be!
>> I've just posted a new (single-module) package to PyPI that simplifies
>> the creation of an argparse UI for a program that consists of a number
>> of subcommands. It uses function docstrings and, optionally,
>> annotations, to put together the necessary argparse configs, without
>> needing all the names to be written out lots of times.
> How is your module different from Docopt?
Oops, I was going to mention something about docopt in the readme,
forgot to actually word anything up. This was partly inspired by
docopt, but docopt still has a lot of the duplication of names. You
have to set up your argument parsing and your functions independently,
and keep them in sync. I could probably have made docstringargs as a
docopt front-end rather than an argparse front-end, and it would have
been roughly the same work.
The basic (and Python 2 compatible) usage still needs a bit of
duplication of names, but it's minimal:
def count(top, step="1"):
"""Count from 1, human style
top: Number to count up to
--step: Increment to count by
If you can restrict yourself to Python 3, you can use annotations instead:
def adduser(user: "Name of user to add", password: "Password for the
"""Add a new user"""
Either way, the definition of the subcommand is entirely in the
function header - there's nothing anywhere else in the program that
defines anything. Synchronization between a function signature and its
own docstring is pretty easy compared to making sure you match names
and functionality in disparate locations - that's the whole point of
docstrings, after all.
Hope that answers that question! I'll nut something out for the readme
at some point.
More information about the Python-list