我可以使用动态映射来解压缩Python中的关键字参数吗?

Aar*_*lin 6 python keyword-argument

长话短说,我想用任意命名的参数调用格式,这将执行查找.

'{Thing1} and {other_thing}'.format(**my_mapping)
Run Code Online (Sandbox Code Playgroud)

我试过像这样实现my_mapping:

class Mapping(object):
  def __getitem__(self, key):
    return 'Proxied: %s' % key
my_mapping = Mapping()
Run Code Online (Sandbox Code Playgroud)

这在调用时按预期工作my_mapping['anything'].但是当传递给如上所示的format()时,我得到:

TypeError: format() argument after ** must be a mapping, not Mapping
Run Code Online (Sandbox Code Playgroud)

我尝试了子类dict而不是object,但现在调用format()如图所示KeyError.我甚至实现__contains__return True,但仍然KeyError.

所以它似乎**不只是调用__getitem__传入的对象.有谁知道如何解决这个问题?

yak*_*yak 6

在Python 2中,您可以使用string.Formatter类来完成此操作.

>>> class Mapping(object):
...     def __getitem__(self, key):
...         return 'Proxied: %s' % key
...
>>> my_mapping = Mapping()
>>> from string import Formatter
>>> Formatter().vformat('{Thing1} and {other_thing}', (), my_mapping)
'Proxied: Thing1 and Proxied: other_thing'
>>>
Run Code Online (Sandbox Code Playgroud)

vformat需要3个参数:格式字符串,位置字段序列和关键字字段的映射.由于不需要位置字段,我使用了一个空元组().


jfs*_*jfs 5

Python 3.2+:

'{Thing1} and {other_thing}'.format_map(my_mapping)
Run Code Online (Sandbox Code Playgroud)