Revision 52 as of 2004-12-01 20:42:03

Clear message

There has been some recent debate about [http://python.org/doc/current/lib/module-ConfigParser.html ConfigParser] on the Python mailing lists. For more, see these threads:

This page serves as a place to record alternatives, and discuss (in a semi-permanent way) the features such a library might have. A new configuration parsing library could go into the Python standard library, probably in addition to the current ConfigParser module (perhaps with that module being deprecated).

Broken Out Sections

Implementations

Please list interesting implementations of config parsers here.

[http://www.voidspace.org.uk/atlantibots/configobj.html ConfigObj - A simple to use config file parser] Not really an alternative to ConfigParser, but a very easy to use config file parser. Dictionary like syntax with the ability to save modified config files. Preserves comments but not indentation.

It allows lists of values against keywords. Will completely read a file if just passed the filename - or read for a specified list of sections/keywords only. Access values like a dictionary - including setting new values. Can save an updated ConfigObj out with a call to it's write method.

M. Chermside's candidate

[http://www.mcherm.com/publish/2004-10-17/config.py code] and [http://www.mcherm.com/publish/2004-10-17/configTest.py test cases]. Currently allows files in either str or unicode, with sensible defaults. Allows dictionary or dotted-name access (though dotted-name can fail in some cases). Allows subsections of arbitrary length. For example,

    x.y = True 
    x.y.z = 47
    x.y.a = prime

Would allow x.y to be viewed as either a value ("True") or a section.

    x.y == "True"

but also

    x.y['a'] = 'prime'
    x.y['z'] = '47'

Note that keys and values are always strings or unicode -- no autoconversion to other types. Note that this focuses on storage and API -- reading and writing is left out at the moment, and might reasonably be in a separate module for each format supported.

.ini file parser and schema

Contains several modules. iniparser is a reusable ini-file parser, with almost no information loss or associated semantics, suitable for reuse. lazyloader can load config files, retain line information and ordering, non-destructively nest configuration files (e.g., you can add and remove config files from the config layering), runtime validation with error messages that specify filename and line number, nested configuration values (using dotted key and section names), and you can compose the configuration files in several ways, for instance superimposing a section onto the main configuration to override configuration based on runtime values.

Available at:

Skip's Idea

In my use of INI files I've always been annoyed that I couldn't nest sections to an arbitrary depth and had to resort to baroque XML APIs to accomplish that sort of task. I also figured a structure defined by indentation would be a good way to go, though YAML always seemed too complex. I worked up a little [http://www.musi-cal.com/~skip/python/cfgparse.py config file parser] that reads and writes files like

empty section1:
level1 = new val
section1:
# this is a comment for section1.item1:
    item1 = item 1
          # this is another comment
    subsection:  
        item2 = item 2
section2:
   subsection:
       item3 = item 3
very last = 7

Dan Gass'

[https://sourceforge.net/projects/config-py/ config-py] allows either strings (safe) or evaluated code (powerful) with the same API. It needs python 2.3, or at least dict.pop()

Vinay Sajip's implementation

The [http://www.red-dove.com/python_config.html config] module allows a hierarchical configuration scheme with support for mappings and sequences, cross-references between one part of the configuration and another, the ability to flexibly access real Python objects without full-blown eval(), an include facility, simple expression evaluation and the ability to change, save, cascade and merge configurations. It has been developed on python 2.3 but should work on version 2.2 or greater.

A simple example - with the example configuration file:

messages:
[
  {
    stream : `sys.stderr`
    message: 'Welcome'
    name: 'Harry'
  }
  {
    stream : `sys.stdout`
    message: 'Welkom'
    name: 'Ruud'
  }
  {
    stream : $messages[0].stream
    message: 'Bienvenue'
    name: Yves
  }
]

a program to read the configuration would be::

from config import Config

f = file('simple.cfg')
cfg = Config(f)
for m in cfg.messages:
    s = '%s, %s' % (m.message, m.name)
    try:
        print >> m.stream, s
    except IOError, e:
        print e

which, when run, would yield the console output::

Welcome, Harry
Welkom, Ruud
Bienvenue, Yves

One problem I have with this implementation is the configuration file syntax. I respect the need for a syntax to handle dictionaries and lists but why invent yet another language? If one wants a Python like syntax make it the Python syntax. I don't think everyone is on board with a Python syntax for configuration files though. My biggest concern is to have a syntax that supports heirarchies and being able to construct Python objects for configuration settings. I lean toward using Python as the syntax (and even the parser) because of the flexibility offered but if there was another way that makes sense I'm ok with that. -- dan.gass@gmail.com

My reasons for not using Python itself for the syntax and parser are:

  1. I couldn't see how to just parse the required subset of Python - lists and dicts - while preventing arbitrary code from being executed.
  2. I wanted to be more forgiving of missing commas.
  3. I wanted to allow easy cross-referencing, inclusion and evaluation, using a more compact notation, which precludes the use of standard Python.

If someone could show me a way to meet the above desires whilst using Python syntax and parser, I'll gladly revisit the issue. -- VinaySajip

cfgparse

[http://www.cs.wisc.edu/~param/software/cfgparse/ cfgparse] - cfgparse is a Python module that provides mechanisms for managing configuration information. It is backward compatible with ConfigParser, in addition to having the following features:

ZConfig

[http://www.zope.org/Members/fdrake/zconfig/ ZConfig] - This Python package is a bit larger than some of the others, but provides for schema-based development of configuration structures. The schema language uses XML, but the configuration language is more like Apache's. Sections are typed and completely nestable.

Features

This is a list of features that should be taken into account. Certainly not all these features are required; maybe some aren't even desired.

To be more explicit, it should work well with at least optparse (Optik), .ini files, .xml files, and computed-at-runtime values. The interface to the various storage mechanisms can be different, but developers shouldn't have to repeat information across the various formats; adding an option (and default value/help message/restrictions) should only need to be done once.

Discussion

Discuss. Please sign your name.

What exactly is the goal? A new API to access configuration info? Or a specific file format itself? Or both? I don't have much problem with the current ConfigParser but ideally I would like use a 'simpler' API. This would allow attribute access (a.b.c) to values, provide default values, convert some types, and do some constraint checking (xyz is required) etc. It's very possible to get this functionality through a wrapper on top of ConfigParser. IMO that is the best approach, as long as there is a way to map the same API over a different underlying file format, such as XML. I think the 'dynamic nesting' point above is outside the scope of the config access API. -- Shalabh

Three features I want in a config parser are 1) keyed settings 2) pulling in settings from multiple configurition files, and 3) ability for user to pass in real python objects through the settings. The "keyed" settings can be thought of as namespaces and I need an arbitrary number of key nestings. For certain applications I EXPECT the user to pass in python objects that meet a specified API. This allows the user to customize a certain operation however they would like with the full power and flexibility of python. I then don't need my tool to be tailered with a switch statement having custom solutions for each user type. This would require the configuration file (or parts of it) to be able to be executed as a python script and I realize this is a security hole that would be unacceptable to many. What I would propose is the config parser module support two methodologies, both sharing the same API and configuration file syntax. One would parse the config file and prevent security issues, the other would either execute the whole config file or be a combination parse/execute but would support attaching real python objects to configuration settings. These features have been implemented in a configuration parser https://sourceforge.net/projects/config-py/ (needs python 2.3 unless the dict pops are reimplemented) and is available for experimentation/use. -- dan.gass@gmail.com 28oct04

I think it is reasonable to ask the setting code to create the object (possibly by running a random string); the config system just needs to accept objects that have already been made. A round-trip is useful, but I'm not sure source code is the best way to do that; editing will probably require an external tool anyhow. Maybe just use pickle to save arbitrary objects? (And avoid storing them *within* the config, as much as possible.) -- Jim J Jewett

ConfigParser, optparse Marriage

A marriage of the two would make a lot of sense to me. My thought is for the user (script) to instantiate a parser and add options to it much like optparse does today. When the parser processes the command line args (or args passed to it) it should also look at the configuration file (possibly using the long setting name) for the option settings. Its first priority would be command line args.

Assume that the config file is simply

#This file is config.cfg
verbose : False

and suppose you want to be able to override this using the command line. One possible program is:

#This is test.py
from config import Config, ConfigList
from optparse import OptionParser

def getMergedConfig(filename):
    optcfg = Config()
    filecfg = Config(filename)
    parser = OptionParser()
    parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='Produce verbose output')
    args = parser.parse_args(None, optcfg)[1]
    cfglist = ConfigList()
    cfglist.append(optcfg)
    cfglist.append(filecfg)
    return cfglist, args

def main():
    cfg, args = getMergedConfig('config.cfg')

    print "verbose output? %r" % cfg.getByPath('verbose')
    print "args: %s" % args

main()

If you run this with

python test.py an_arg

the output is

verbose output? False
args: ['an_arg']

whereas if you run this with

python test.py -v an_arg

the output is

verbose output? True
args: ['an_arg']

This admittedly simple example points to how simple the actual application code - i.e. main() could be. I'm assuming that getMergedConfig() is a utility function which could be shared across multiple scripts, but even so it is pretty simple, in my view. Notice that main() does not know where the configured value of 'verbose' came from.

To forestall the complaint that the optparse specification appears to require some duplication, you could change the config file to:

#This file is config.cfg
verbose : False
optparse:
[
  { name: verbose, short: '-v', long: '--verbose', action: 'store_true', default: None, help: 'Produce verbose output'}
]

and the code which sets the parser options to (indent appropriately):

for optspec in filecfg.optparse:
    parser.add_option(optspec.short, optspec.long, action=optspec.action, dest=optspec.name, help=optspec.help)

Remember, this is just one way of doing it - not the only way and perhaps not the best way for your needs, but a simple enough way.

-- VinaySajip

A hierarchical “key” or “namespace” scheme should exist so that multiple settings may be stored in the user configuration file. I would propose a standard -k, –key option always present in the parser so the user can pass a list of keys to control the group of settings to use (I’d also like some of the other ways to control keys that I use in my config.py module). In addition I’d propose a -c, –config option that specifies a configuration file to use instead of the user’s default configuration file.

My last proposal for today is to change the “options” interface a bit from optparse. Instead of returning a static object of options it should be an object with a get() method so that additional keys can be used to get at settings in the configuration “on the fly”. One application where this is important is in test frameworks. “Test specification” input files may have additional “keys” to be used and aren’t known when the parser is instantiated.

path = sys.platform + ".database.connection"
connstr = cfg.getByPath(path)

One benefit of this marriage is that the help messages available from the command line would also apply to what can be set in the configuration file. Also there is a lot of flexibility for the user with this scheme. For options they always use they can hard code them in their default configuration as settings. If they want to temporarily override them they can use command line options. For groups of settings that are always used together, they can be used by simply passing in a key with the -k option to select the group.

The part that isn’t addressed here that bothers me yet is how to weave in the ability to pass in real python objects as settings. It would be good to have both a secure (restricted to strings and simple settings) and a second less than secure parser for those applications that need the flexibility of python. I’d like to see the API’s of the same for both the parser and the configuration file. -- dan.gass@gmail.com

My Dramatic Plea

Syntax Proposal, Tweak ConfigParser .ini Syntax To Allow Arbitrary Nesting Levels

Please take a look at this sample configuration file and comment. It is extremely similar to the .ini syntax of ConfigParser but allows arbitrarily deep nesting. I also figured out a way to have my cake and eat it too as far as being able to use execfile to bring in settings (strictly an option for us insane types).

# just like ConfigParser 
#   : and = are interchangeable and are used for assigning values to options
#   # and ; are interchangeable and are used for comments
#   %(option)s still works the same
#
# [ ] means more.  When used alone it still defines a section.  It also
# defines a list of keys to use to place option into a dictionary.
#
# options surrounded by < > are special
#   <keys> defines a comma separated list of default keys to use when 
#          traversing an option dicationary when retrieving an option.
#          Note, these keys will optionally be supplemented with keys 
#          from the command line.
#
#   <read> defines a comma separated list of additional configuration files 
#          to read.  By default, it expects the configuration file to have 
#          this syntax style.  If application optionally selects allowing 
#          python files to execute (done during parser instantiation?) and the 
#          file has a .py extension then execfile is used to read the options 
#          from the file and merge them into the options dictionaries.
#
# For example:

                                 # start of section [] is assumed
<keys> : grpA,dev0,sb1           # by default use these keys to get options
<read> : more.cfg,evenmore.cfg   # opt=val for opt,val in cfg.py
comm_driver = standard           # same as comm_driver = 'standard'
comm_path[grpA,dev0] = path_A0   # same as comm_path['grpA']['dev0'] = 'path_A0'
comm_path[grpA,dev1] = path_A1   # same as comm_path['grpA']['dev1'] = 'path_A1'

[sb1]                            # starts a new section
sandbox = /home/dmgass/build_v1  # inserts this value under sandbox['sb1']
<read> = %(sandbox)s/cfg.py      # [ opt['sb1']=val for opt,val in cfg.py ] :-)

[sb2]                            # starts a new section
sandbox = /home/dmgass/build_v2  # inserts this value under sandbox['sb2']
<read> = %(sandbox)s/cfg.py       # [ opt['sb1']=val for opt,val in cfg.py ] :-)

[grpB]                           # starts a new section
comm_path[dev0] = path_B0        # same as comm_path['grpB']['dev0'] = 'path_B0'
comm_path[dev1] = path_B1        # same as comm_path['grpB']['dev1'] = 'path_B1'

[grpC,dev0]                      # starts a new section
comm_path = path_C0              # same as comm_path['grpC']['dev0'] = 'path_C0'

[grpC,dev1]                      # starts a new section
comm_path = path_C1              # same as comm_path['grpC']['dev1'] = 'path_C1'

# In theory user could override default keys specified in this file from 
# the command line to communicate with device 1 of group C:
#   application.py --keys=dev1,grpC

I've been tinkering with a "cooperation" between optparse and a new configuration parser to get the benefits described earlier without the design, implementation, and documentation headaches. More on this later after I get more sleep and do more research. -- dan.gass@gmail.com

Complexity killed the cat!

Look at what happened to urllib2 - the entry level for new users was greatly enhanced, but the added functionality was really little more than what you could already do more simply with urllib. With that in mind, I think the new ConfigParser should in it's simplest form act very closely like the original ConfigParser.

Unable to edit the page? See the FrontPage for instructions.