Referencing section name by interpolation in ConfigParser

Peter Otten __peter__ at web.de
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 
%{...}s:

$ cat config.ini
[Foo]
secref: %(section)s/whatever
[Bar]
secref: %(section)s/whatever
$ cat demo.py
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())
p.read("config.ini")
for section in "Foo", "Bar":
    print(section, "-->", p[section]["secref"])
$ python3 demo.py 
Foo --> Foo/whatever
Bar --> Bar/whatever
$



More information about the Python-list mailing list