[Python-ideas] Add a begins like wrapper to argparse

Michel Desmoulin desmoulinmichel at gmail.com
Sat Mar 26 07:02:58 EDT 2016


I love argparse. I really do. But it's one of those lib forcing me to
RTFM everytime I need it, for the last 10 years.

We had pathlib added to the stdlib to help with open/os/shutil API and
we could do the same with argparse.

There are many libs helping with argparsing (clize, click, argh, docopt,
etc), and I'd like to talk about the API of one of them, begins.

You define the entry point of your script as a regular function you
decorate:

>>> import begin
>>> @begin.start
... def run(name='Arther', quest='Holy Grail', colour='blue', *knights):
...     "tis but a scratch!"


@begin.start will do "if __name__ == '__main__'" for you (alhough you
can opt out), and parse the function arguments then generate a argparse
parser.

When you call the script, it parses the arguments, and call your
function with them passed as parameters. It also generates the --help:

usage: example.py [-h] [-n NAME] [-q QUEST] [-c COLOUR]
                  [knights [knights ...]]

tis but a scratch!

positional arguments:
  knights

optional arguments:
  -h, --help            show this help message and exit
  -n NAME, --name NAME  (default: Arther)
  -q QUEST, --quest QUEST
                        (default: Holy Grail)
  -c COLOUR, --colour COLOUR
                        (default: blue)

Of course, you can define more behavior using other decorators such as
repetition, type, checks and sub commands.

It's not a huge lib, but's it makes writting script out of the box a
breeze. The only problem is : you usually don't want to do a pip install
just to run a script. That's why I things it would be great to have
something similar in the stdlib.

What's more, it's really not going to evolve much (you can't get more
old school than cmd), so having it not be updated for years after
including it (or something like it) in the stdlib is not an issue.

And we can even add some features that would be useful to benefit from
the last Python goodness, such as an option to auto-spawn an event loop.
This way you can create a quick script with just an async def function.
Indeed, the boiler plate of getting the event loop, adding a coroutine
and starting the loop is getting annoying very fast when you do a lot of
quick things with any aio libs.


More information about the Python-ideas mailing list