Introducing uberparse

Overview

uberparse is a Python library which reduces the burden of handling command line and configuration file parsing for modules and applications, making it trivial for imported modules to recursively expose configuration options and command line arguments.

In essence, uberparse is a thin wrapper around ConfigParser and optparse, but it presents them in a coherent and very simple way. Options are defined as attributes of a class, and a single function call transparently handles all of the configuration and argument parsing.

A simple example

Below is the simplest possible uberparse example:

import uberparse

class ModuleFlags(uberparse.FlagClass):
test_flag = dict(default="value", help="a test flag", short="-t")

options, args = uberparse.ParseOptions()

print "Test flag:", options["test_flag"]

This gets you the following for free:

$ ./test.py --help
Usage: test.py [options]

Options:
-h, --help show this help message and exit
--help-application
--help-builtin

Options for application:
-t TEST_FLAG, --test_flag=TEST_FLAG
a test flag

Options for builtin:
-c CONFIG, --config=CONFIG
path to configuration file
--genconf dump configuration options and exit

$ ./test.py --test_flag=hello
Test flag: hello

$ ./test.py -t hello
Test flag: hello

It’s also trivial to create custom configuration files:

[application]

test_flag = config value

Builtin flags

You get –help, –help-xxx, –config, and –genconf options for free when using uberparse. The more precise –help options are useful for managing very large, nested sets of flags. The –genconf option will dump a valid configuration file with the current options, comments and values to the console.

Settings

The operation of uberparse can be configured on a per-application basis using another settings class. For example, you could configure the default config file using the following in your module:

class FlagSettings(uberparse.SettingsClass):
config = "test.ini"
include = ('some_test_module',)

Any class name can be used, so long as it inherits from uberparse.SettingsClass.

Module flags

As mentioned briefly earlier, any imported modules will also have their flags parsed. The unified configuration file is capable of configuring options from imported modules as well as the main application. Flags are defined in modules the same way they are defined in the main application.

The include setting from SettingsClass can be used to selectively import flags from specific modules. The default behavior is to use flags defined in any imported module.

Gimme!

You can grab the source code and a more comprehensive example here.

Leave a Reply