Referencing section name by interpolation in ConfigParser

Hans-Peter Jansen hpj at urpla.net
Fri Jan 27 09:23:53 EST 2017


On Mittwoch, 25. Januar 2017 10:01:56 Peter Otten wrote:
> 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:

Yes, of course.. Sorry for the typo.

> $ 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
> $

Brilliant as usual, thank you, Peter.

This is exactly, what I was after.

Have a nice weekend,
Pete


More information about the Python-list mailing list