Why ** kwargs interpolate with python ConfigObj?

I am using ConfigObj in python with template style interpolation. Deploying my configuration dictionary via ** does not seem to do the interpolation. Is this a sign or a mistake? Any good workarounds?

$ cat my.conf foo = /test bar = $foo/directory >>> import configobj >>> config = configobj.ConfigObj('my.conf', interpolation='Template') >>> config['bar'] '/test/directory' >>> '{bar}'.format(**config) '$foo/directory' 

I expect the second line to be /test/directory . Why doesn't interpolation work with ** kwargs?

+7
source share
2 answers

When unpacking the keyword argument, a new object is created: of type dict . This dictionary contains the original configuration values ​​(no interpolation)

Demonstration:

 >>> id(config) 31143152 >>> def showKeywordArgs(**kwargs): ... print(kwargs, type(kwargs), id(kwargs)) ... >>> showKeywordArgs(**config) ({'foo': '/test', 'bar': '$foo/directory'}, <type 'dict'>, 35738944) 

To solve your problem, you can create an advanced version of your configuration as follows:

 >>> expandedConfig = {k: config[k] for k in config} >>> '{bar}'.format(**expandedConfig) '/test/directory' 

Another elegant way is simply to avoid unpacking: this can be achieved using the string.Formatter.vformat function:

 import string fmt = string.Formatter() fmt.vformat("{bar}", None, config) 
+2
source

I had a similar problem.

A workaround is to use the configobj function ".dict ()". This works because configobj returns a real dictionary that Python knows how to unpack.

Example:

 >>> import configobj >>> config = configobj.ConfigObj('my.conf', interpolation='Template') >>> config['bar'] '/test/directory' >>> '{bar}'.format(**config.dict()) '/test/directory' 
+2
source

All Articles