Parsing environment variables in ConfigParser files

Peter Otten __peter__ at
Fri Dec 19 19:21:01 CET 2003

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.get("paths", "mydir")
>>> p.getexpanded("paths", "mydir")

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.


More information about the Python-list mailing list