Why doesn't **kwargs interpolate with python ConfigObj?
我在python中使用configobj和模板样式的插值。通过**打开我的配置字典似乎不需要进行插值。这是一个特性还是一个bug?有什么好的解决办法吗?
1 2 3 4 5 6 7 8 9 10 | $ 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' |
我希望第二行是
我已经有一个类似的问题。
一个workaround configobj的功能是使用".dict()"。一个真正的作品,因为这configobj returns Python字典,其中unpack知道如何。
你的例子变成:
1 2 3 4 5 6 | >>> import configobj >>> config = configobj.ConfigObj('my.conf', interpolation='Template') >>> config['bar'] '/test/directory' >>> '{bar}'.format(**config.dict()) '/test/directory' |
当unpacking argument前,然后是一个新的面向对象的创建:
演示:
1 2 3 4 5 6 7 | >>> id(config) 31143152 >>> def showKeywordArgs(**kwargs): ... print(kwargs, type(kwargs), id(kwargs)) ... >>> showKeywordArgs(**config) ({'foo': '/test', 'bar': '$foo/directory'}, <type 'dict'>, 35738944) |
大的问题,你可以创建一resolve扩版的configuration,像这样:
1 2 3 | >>> expandedConfig = {k: config[k] for k in config} >>> '{bar}'.format(**expandedConfig) '/test/directory' |
另一个更优雅的方式是将avoid unpacking:这是可以由使用功能achieved string.formatter.vformat:
1 2 3 | import string fmt = string.Formatter() fmt.vformat("{bar}", None, config) |