[Python-Dev] ConfigParser with a single section

Detlef Lannert lannert-pydev@lannert.rz.uni-duesseldorf.de
Fri, 8 Nov 2002 16:50:56 +0100


[Gustavo Niemeyer]
> Patch #549037 implements an interesting feature: it allows one to have
> configuration files without headers. I'd like to know what's your
> opinion about this issue, so that we can either forget the issue or
> implement the functionality, closing that bug.

[Tim Peters]
> -0.  Complicates the code and the docs and the mental model to save what, 3
> measly characters of typing (e.g., "[x]")?

It also saves me to explain to the users of my program why they _have_ to
start each configuration file with a line containing "[Options]", even if
there can't be anything other than options in this file.  (Making them type
"[x]" instead of "[Options]" is even harder <.5 wink>).

Unfortunately I cannot easily supply the section line when parsing the
config file, even if I use ConfigParser.readfp(); the "obvious solution"

    prefix = cStringIO.StringIO("[Options]\n")
    cfp = ConfigParser.ConfigParser()
    cfp.readfp(prefix, filename)
    cfp.read(filename)

doesn't work because the ConfigParser object expects a new section header
for each read*() call.

A generator that encapsulates the file and supplies an initial section
header doesn't work either because the ConfigParser uses the readline()
method; it doesn't iterate over the file.

Subclassing the ConfigParser class doesn't help much because the _read()
method does most of the relevant work and at the same time requires the
section header line.  So this would basically mean I had to copy that
method (~60 lines) and tweak it to handle the case of missing section
headers.  [I had tried this before I submitted the patch.]

[Gustavo Niemeyer, in a preceding mail]
> The patch includes a new parameter in read functions, stating
> what's the first section name. It means that we could have other
> sections after the first unheaded section. IMO, that situation should
> still be considered an error.

Not necessarily an error; I was thinking of a configuration file like

    spam = available
    frob = required
    # ... more general options
    
    [Holidays]
    frob = optional
    # ... more options for a special case
    
    # etc.

where labelled, optional sections may follow the (usually unlabelled)
main configuration section.  If the caller doesn't want this, he can
easily detect this situation (checking cfp.sections()) and reject/handle
it.

  Detlef