为什么 **kwargs 不与 python ConfigObj 插值?



我在python中使用ConfigObj和Template风格的插值。通过 ** 解开我的配置字典似乎没有进行插值。 这是一个功能还是一个错误? 有什么不错的解决方法吗?

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

我希望第二行是/test/directory. 为什么插值不适用于 **kwargs?

解压缩关键字参数时,将创建一个新对象:类型为 dict 。此字典包含配置的原始值(无插值)

示范:

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

要解决您的问题,您可以创建配置的扩展版本,如下所示:

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

另一种更优雅的方法是简单地避免解包:这可以通过使用函数字符串来实现。格式化程序.vformat:

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

我也有类似的问题。

解决方法是使用 configobj 的函数 ".dict()"。这是有效的,因为configobj返回了一个真正的字典,Python知道如何解压缩。

您的示例变为:

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

最新更新