Opterator, revisited

By | December 8, 2012

A few years ago, I wrote a simple decorator that introspects a main() method signature and docstring to generate an option parser. I never really used it, mostly because back then, I wasn’t too keen on third party dependencies. Nowadays with distribute being maintained, well-documented, and working (plus I know how to use it properly), I no longer have this concern.

A friend recently linked me to the brilliantly designed docopt and reminded me of my interest in opterator. I revisited my code and decided it’s a pretty neat little design. So I ported it to Python 3. This took a matter of minutes, largely because I originally wrote it shortly after taking the pytest tutorial at Pycon 2009 and it was easy to find the failing code. It now supports Python 2.6, 2.7, and 3.3, according to tox.

I originally designed opterator to be a full replacement for optparse and friends. However, my main purpose for it now is to create quick and dirty command line applications, often for my personal use. These apps usually have a couple of options and it doesn’t seem worth the trouble of setting up optparse. Yet, mucking around with sys.argv is also annoying. Opterator minimizes the boilerplate. Check out this basic example:

with three lines of boilerplate code, a function can be turned into a command line program that can be called like so:

or so:

or even so:

And you even get a not totally (but somewhat) useless helpfile:

3 thoughts on “Opterator, revisited

  1. Wyatt Baldwin

    I noticed in your setup.py you have from setuptools import setup instead of from distutils.core import setup. Do you know if there’s any reason to use the setuptools setup() instead of the distutils version when you’re not also using other features from setuptools (e.g., find_packages())?

  2. Kevin Dahlhausen

    That’s great – I hope to use it in the future. I love how it takes all of the work out of setting up the options parser. Thanks for posting it.


Leave a Reply

Your email address will not be published. Required fields are marked *