【问题标题】:How do I add __format__ to a namedtuple in Python 3.5+?如何在 Python 3.5+ 中将 __format__ 添加到命名元组?
【发布时间】:2017-08-11 00:30:13
【问题描述】:

我正在使用为早期版本的 Python 编写的代码。

TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])

稍后,我有这个(删节的)代码:

s = [hdr, '-' * 94]
...
s.append('{:<20} {:<30} {:>20} {:>20}'.format(node.kind, node.name, data_shape,
                                                          tuple(out_shape)))

tuple(out_shape) 上爆炸了,但例外

TypeError: unsupported format string passed to tuple.__format__

因为out_shapeTensorShape 并且它没有定义__format__ 方法。

所以我将TensorShape 的定义更改为

def format_tensorshape(format_spec):
    return format("{0} {1} {2} {3}")

TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
TensorShape.__format__ = format_tensorshape

但是这段代码仍然会在下游发生同样的异常。

我做错了什么?

【问题讨论】:

  • 当应用于元组时,您期望{:&gt;20} 的行为是什么?调用tuple(out_shape) 是一个空操作(out_shape 已经是一个元组),但是如果你想将它显示为(batch_size, channels, height, width),你可以简单地调用str(out_shape)。由于这是一个字符串,格式化指令应该可以按预期工作。
  • @larsks 如果你使用 str(out_shape) 那么你会得到类和方法的名称以及值,而不是(batch_size、channels、height、width)。
  • 对,str(tuple(...)),我猜。

标签: python string python-3.x string-formatting


【解决方案1】:

你在正确的轨道上——只需将传递给format_tensorshapetwo arguments连接到你对format的调用:

import collections
def format_tensorshape(self, format_spec):
    return format("{0} {1} {2} {3}".format(*self), format_spec)

TensorShape = collections.namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
TensorShape.__format__ = format_tensorshape

out_shape = TensorShape(1,2,3,4)
print('{:>20}'.format(out_shape))

产量

             1 2 3 4

【讨论】:

    【解决方案2】:

    您可以简单地使用基于字符串表示的格式。这可以通过!s 转换标志实现,因为字符串知道如何解释您的格式规范,因此无需为您的namedtuple 创建自定义__format__ 方法:

    s.append('{:<20} {:<30} {:>20} {!s:>20}'.format(node.kind, node.name, data_shape,
                                                    tuple(out_shape)))
    #                               ^^---- here I added the !s
    

    例如:

    >>> from collections import namedtuple
    >>> TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
    >>> '{!s:>20}'.format(tuple(TensorShape(1,1,1,1)))
    '        (1, 1, 1, 1)'
    

    【讨论】:

      猜你喜欢
      • 2016-09-16
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 2022-06-10
      • 2010-12-09
      • 1970-01-01
      • 2013-03-05
      相关资源
      最近更新 更多