RE: Parsing environment variables in ConfigParser files

From: Robert Brewer (fumanchu_at_amor.org)
Date: 12/19/03


Date: Fri, 19 Dec 2003 10:37:21 -0800
To: <python-list@python.org>

Does this snippet from ConfigParser.py give anyone any ideas on how to
do this without subclassing? ;)

class RawConfigParser:
    def __init__(self, defaults=None):
        self._sections = {}
        if defaults is None:
            self._defaults = {}
        else:
            self._defaults = defaults

    def defaults(self):
        return self._defaults

>>From the docs: "Default values can be specified by passing them into the
ConfigParser constructor as a dictionary. Additional defaults may be
passed into the get() method which will override all others."

Let's not patch in a single use case when a simple generic solution
already presents itself.

Robert Brewer
MIS
Amor Ministries
fumanchu@amor.org

> -----Original Message-----
> From: Peter Otten [mailto:__peter__@web.de]
> Sent: Friday, December 19, 2003 10:21 AM
> To: python-list@python.org
> Subject: Re: Parsing environment variables in ConfigParser files
>
>
> Matthew Barnes wrote:
>
> > I'm considering submitting a patch for Python 2.4 to allow
> environment
> > variable expansion in ConfigParser files. The use cases for this
> > should be obvious. I'd like to be able to specify
> something like the
> > following in a configuration file:
> >
> > [section_name]
> > data_file=${HOME}/mydata.dat
> >
> > ...(where HOME=/home/matt) and have ConfigParser
> automatically expand
> > it to:
> >
> > [section_name]
> > data_file=/home/matt/mydata.dat
> >
> > The change is pretty straight-forward, but I'm interested
> in feedback
> > on whether this is a good idea, what the syntax for environment
> > variable references should look like (currently I'm thinking
> > ${varname}), or whether there are any hidden complexities or
> > backward-compatibility concerns.
> >
> > Matthew Barnes
>
> I think this can be easily achieved by subclassing the ConfigParser:
>
> >>> from ConfigParser import ConfigParser
> >>> class ExpandingParser(ConfigParser):
> ... def getexpanded(self, section, option):
> ... import os
> ... return self._get(section, os.path.expandvars, option)
> ...
> >>> p = ExpandingParser()
> >>> p.read("expand.ini")
> >>> p.get("paths", "mydir")
> '$HOME/of/the/brave'
> >>> p.getexpanded("paths", "mydir")
> '/home/peter/of/the/brave'
> >>>
>
> If you will bother with the library implementation at all, I
> would prefer
> this level of explicitness, i. e. a dedicated getexpanded() method in
> ConfigParser, or alternatively a subclass that overrides
> _get() to always
> expand in the getXXX() methods. With both approaches you can
> stay safely
> away from backwards compatibility problems.
>
> Peter
>
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>