Referencing section name by interpolation in ConfigParser

Peter Otten __peter__ at
Wed Jan 25 04:01:56 EST 2017

Hans-Peter Jansen wrote:

> I would like to use a interpolated section name, e.g.:
> [Section]
> secref: %{section}s/whatever
> should result in:
>>>> config['Section']['secref']
> 'Section/whatever'
> Any idea anybody, how to archive this with minimum fuzz?

If you can live with the existing "basic interpolation", i. e. %(...)s, not 

$ cat config.ini
secref: %(section)s/whatever
secref: %(section)s/whatever
$ cat
import configparser

class Interpolation(configparser.BasicInterpolation):
    def before_get(self, parser, section, option, value, defaults):
        defaults = defaults.copy()
        defaults["section"] = section
        return super().before_get(parser, section, option, value, defaults)

p = configparser.ConfigParser(interpolation=Interpolation())"config.ini")
for section in "Foo", "Bar":
    print(section, "-->", p[section]["secref"])
$ python3 
Foo --> Foo/whatever
Bar --> Bar/whatever

More information about the Python-list mailing list