3

当我尝试运行此代码时:

from pprint import PrettyPrinter

class MyPrettyPrinter(PrettyPrinter):
    def __init__(self, *args, **kwargs):
        PrettyPrinter.__init__(self, *args, **kwargs)
    def format(self, object, context, maxlevels, level):
        (repr, readable, recursive) = PrettyPrinter.format(self, object, context, maxlevels, level)
        return (type(repr)(object), readable, recursive) if isinstance(object, str) else (repr, readable, recursive)

print(MyPrettyPrinter().pformat(['x']))

我在 Python 3 ( )中得到的输出与在Python 2 ( ) 中得到的输出不同。['x'][x]

为什么会这样,如何获得与 Python 2 中相同的行为?

4

1 回答 1

2

Python 3 的内部_format函数是这样工作的:

def _format(self, object, stream, indent, allowance, context, level):
    # …
    rep = self._repr(object, context, level - 1)
    max_width = self._width - 1 - indent - allowance
    sepLines = len(rep) > max_width

    if sepLines:
        # … custom repr logic
    write(rep)

如您所见,如果输出_repr适合单行,则不使用自定义逻辑来生成 repr。self._repr委托给self.format,这实际上只是做了一个更复杂的repr(). 因此,如果输出适合单行,则只调用一次;否则,不使用输出,但(此处:序列)元素被拆分为多个部分,并且再次为子元素调用逻辑。

相比之下,Python 2_format在任何阶段都实现了完全自定义的逻辑,总是为列表中的所有子元素调用自定义格式化程序。这就是为什么您的触发器在 Python 2 中有效但在 Python 3 中无效的原因。

不幸的是,如果不复制新的 Python 3 实现中的大量逻辑,我看不到任何简单的方法来解决这个问题。

于 2015-08-23T19:07:58.103 回答