gpt4 book ai didi

python - 为什么 **kwargs 不使用 python ConfigObj 进行插值?

转载 作者:太空狗 更新时间:2023-10-29 21:53:29 24 4
gpt4 key购买 nike

我正在使用 ConfigObj在带有模板样式插值的 python 中。通过 ** 打开我的配置字典似乎没有进行插值。这是功能还是错误?有什么好的解决方法吗?

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

另一种更优雅的方法是简单地避免解包:这可以通过使用函数 string.Formatter.vformat 来实现。 :

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

关于python - 为什么 **kwargs 不使用 python ConfigObj 进行插值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11314068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com