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)

ご覧のとおり、 の出力が_repr1 行に収まる場合、repr を生成するためのカスタム ロジックは使用されません。self._reprに委任しますself.format。これは本質的に、より複雑なrepr(). したがって、出力が 1 行に収まる場合、これは 1 回だけ呼び出されます。それ以外の場合、出力は使用されませんが、(ここではシーケンス) 要素が複数の部分に分割され、サブ要素に対してロジックが再度呼び出されます。

対照的に、Python 2_formatはどの段階でも完全にカスタムのロジックを実装し、常にリスト内のすべてのサブ要素に対してカスタム フォーマッタを呼び出します。そのため、トリガーは Python 2 では機能しますが、Python 3 では機能しません。

残念ながら、新しい Python 3 実装にある多くのロジックを複製せずに、これにフックする簡単な方法は見当たりません。

于 2015-08-23T19:07:58.103 に答える