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

标签 python keyword-argument

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

'{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/

相关文章:

python - 格式化 timedelta 对象

python - 从 Google Contacts API 3.0 版获取所有联系人

python - 如何修复Python中的“'numpy.ndarray'对象不可调用”错误?

python - 当应该影响 X 的变量发生变化时,变量 X 不更新

common-lisp - Common Lisp 中 &rest 和 &key 参数的 Lambda 列表错误

python - 检查 **kwargs 中的值的更简单方法

python - 如何使用 Sphinx 显示与文本内嵌的键盘按键图片?

python - 创建 GAE 实体时遇到问题

python - 将 Python dict 转换为 kwargs?

python - 如何在 Django 过滤器的 kwargs 中传递用户名?