长话短说,我想用任意命名的参数调用格式,这将执行查找。
'{Thing1} and {other_thing}'.format(**my_mapping)
我试过像这样实现 my_mapping:
class Mapping(object):
def __getitem__(self, key):
return 'Proxied: %s' % key
my_mapping = Mapping()
调用 my_mapping['anything']
时按预期工作。但是当如上所示传递给 format() 时,我得到:
TypeError: format() argument after ** must be a mapping, not Mapping
我尝试子类化 dict
而不是 object
,但现在调用 format()
会引发 KeyError
。我什至将 __contains__
实现为 return True
,但仍然是 KeyError
。
所以看来 **
不仅仅是在传入的对象上调用 __getitem__
。有人知道如何解决这个问题吗?
最佳答案
在 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'
>>>
vformat
接受 3 个参数:格式字符串、位置字段序列和关键字字段映射。由于不需要位置字段,我使用了一个空元组 ()
。
关于python - 我可以使用动态映射来解压缩 Python 中的关键字参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8218652/