7

テンプレートスタイルの補間を使用してPythonでConfigObjを使用しています。** を介して構成辞書をアンラップしても、補間が行われないようです。これは機能ですか、それともバグですか? 良い回避策はありますか?

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

2 行目は/test/directory. **kwargs で補間が機能しないのはなぜですか?

4

2 に答える 2

2

キーワード引数をアンパックすると、新しいオブジェクトが作成されます: タイプ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'

もう 1 つのより洗練された方法は、単純にアンパックを回避することです。これは、関数string.Formatter.vformatを使用して実現できます。

import string
fmt = string.Formatter()
fmt.vformat("{bar}", None, config)
于 2012-07-05T08:33:31.423 に答える
2

I have had a similar problem.

A workaround is to use configobj's function ".dict()". This works because configobj returns a real dictionary, which Python knows how to unpack.

Your example becomes:

>>> import configobj
>>> config = configobj.ConfigObj('my.conf', interpolation='Template')
>>> config['bar']
'/test/directory'
>>> '{bar}'.format(**config.dict())
'/test/directory'
于 2012-09-29T14:03:08.220 に答える