Opterator, revisited

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:

from opterator import opterate                      

def main(filename, color='red', verbose=False):     
    print(filename, color, verbose)


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

  $ python examples/basic.py this_file
  this_file red False

or so:

  python examples/basic.py this_file --color=blue
  this_file blue False

or even so:

  $ python examples/basic.py --color=purple another_file --verbose
  another_file purple True

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

  $ python examples/basic.py -h
  Usage: basic.py [options] filename

  -h, --help            show this help message and exit
  -c COLOR, --color=COLOR
  -v, --verbose


  1. 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. Nice, clever, Pythonic! Thanks for sharing it.

  3. Kevin Dahlhausen says:

    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.