docstringargs: Python module for setting up argparse

Chris Angelico rosuav at gmail.com
Tue Apr 21 06:39:51 CEST 2015


On Tue, Apr 21, 2015 at 2:33 PM, Paul Rubin <no.email at nospam.invalid> wrote:
> Chris Angelico <rosuav at gmail.com> writes:
>> @cmdline
>> def adduser(
>>         user: {cmdline: "Name of user to add", typing: str},
>>         password: {cmdline: "Password for the new user", typing: str}=""):
>>     """Add a new user"""
>
> In the case of just one decorator, the dictionary could be omitted.  The
> decorator function itself could have an annotation flagging it as a
> consumer of annotations, so that would make it easy to check if there
> was more than one.  In your example above, you'd also want a @typing
> decorator.

PEP 484 says that type hints don't need a decorator, but if it were
anything else, then yes, it'd need a second decorator. But what if one
of the annotation usages wants to be a dictionary? How can you elide
the outer dictionary and still recognize what's going on?

> In those particular cases, the decorators don't even need the annotation
> feature:
>
> @cmdline(name="Name of user to add", password="Password for the new user")
> @typing(name=str, password=str)
> def adduser(user, password):
>     """Add a new user"""
>     ...

And that's a completely different feature. It still has the advantage
that everything is right there in the function signature... but look
how easy it is to introduce bugs: you're inconsistent about whether
the first parameter is called "name" or "user". This is exactly why
annotations exist. Like decorators themselves, they reduce repetition
and thus bugs.

ChrisA



More information about the Python-list mailing list