pprint —データプリティプリンター—Pythonドキュメント

提供:Dev Guides
< PythonPython/docs/3.9/library/pprint
移動先:案内検索

pprint —データプリティプリンター

ソースコード: :source: `Lib / pprint.py`



pprint モジュールは、インタプリタへの入力として使用できる形式で任意のPythonデータ構造を「きれいに印刷」する機能を提供します。 フォーマットされた構造に基本的なPythonタイプではないオブジェクトが含まれている場合、表現をロードできない可能性があります。 これは、ファイル、ソケット、クラスなどのオブジェクトや、Pythonリテラルとして表現できない他の多くのオブジェクトが含まれている場合に当てはまります。

フォーマットされた表現は、可能であればオブジェクトを1行に保持し、許可された幅に収まらない場合は複数の行に分割します。 幅の制約を調整する必要がある場合は、 PrettyPrinter オブジェクトを明示的に作成します。

辞書は、表示が計算される前にキーでソートされます。

バージョン3.9で変更:プリティプリント types.SimpleNamespace のサポートが追加されました。


pprint モジュールは、次の1つのクラスを定義します。

class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True)

PrettyPrinter インスタンスを作成します。 このコンストラクターは、いくつかのキーワードパラメーターを理解します。 出力ストリームは、 stream キーワードを使用して設定できます。 ストリームオブジェクトで使用される唯一のメソッドは、ファイルプロトコルのwrite()メソッドです。 指定しない場合、 PrettyPrintersys.stdoutを採用します。 各再帰レベルに追加されるインデントの量は、 indent で指定されます。 デフォルトは1です。 他の値を使用すると、出力が少し奇妙に見える可能性がありますが、ネストを見つけやすくすることができます。 印刷できるレベルの数は、深度によって制御されます。 印刷されるデータ構造が深すぎる場合、次に含まれるレベルは...に置き換えられます。 デフォルトでは、フォーマットされるオブジェクトの深さに制約はありません。 必要な出力幅は、 width パラメーターを使用して制限されます。 デフォルトは80文字です。 構造が制限された幅内でフォーマットできない場合は、最善の努力が払われます。 Compact がfalse(デフォルト)の場合、長いシーケンスの各項目は別々の行にフォーマットされます。 Compact がtrueの場合、 width 内に収まる数のアイテムが各出力行でフォーマットされます。 sort_dicts がtrue(デフォルト)の場合、辞書はキーがソートされた状態でフォーマットされます。それ以外の場合、辞書は挿入順に表示されます。

バージョン3.4で変更: コンパクトパラメーターが追加されました。

バージョン3.8で変更: sort_dicts パラメーターが追加されました。

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']
>>> pp = pprint.PrettyPrinter(width=41, compact=True)
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberjack',
  'knights', 'ni'],
 'spam', 'eggs', 'lumberjack', 'knights',
 'ni']
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))

pprint モジュールは、いくつかのショートカット機能も提供します。

pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)

オブジェクトのフォーマットされた表現を文字列として返します。 インデント深さコンパクトsort_dictsPrettyPrinter に渡されます]フォーマットパラメータとしてのコンストラクタ。

バージョン3.4で変更: コンパクトパラメーターが追加されました。

バージョン3.8で変更: sort_dicts パラメーターが追加されました。

pprint.pp(object, *args, sort_dicts=False, **kwargs)

オブジェクトのフォーマットされた表現とそれに続く改行を出力します。 sort_dicts がfalse(デフォルト)の場合、辞書は挿入順にキーとともに表示されます。それ以外の場合、辞書キーはソートされます。 args および kwargs は、フォーマットパラメータとして pprint()に渡されます。

バージョン3.8の新機能。

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)

オブジェクトのフォーマットされた表現をストリームに出力し、その後に改行を続けます。 ストリームNoneの場合、sys.stdoutが使用されます。 これは、値を検査するために print()関数の代わりに対話型インタープリターで使用できます(スコープ内で使用するためにprint = pprint.pprintを再割り当てすることもできます)。 インデント深さコンパクトsort_dictsPrettyPrinter に渡されます]フォーマットパラメータとしてのコンストラクタ。

バージョン3.4で変更: コンパクトパラメーターが追加されました。

バージョン3.8で変更: sort_dicts パラメーターが追加されました。

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff)
>>> pprint.pprint(stuff)
[<Recursion on list with id=...>,
 'spam',
 'eggs',
 'lumberjack',
 'knights',
 'ni']
pprint.isreadable(object)

オブジェクトのフォーマットされた表現が「読み取り可能」であるか、または eval()を使用して値を再構築するために使用できるかどうかを判別します。 これは、再帰オブジェクトに対して常にFalseを返します。

>>> pprint.isreadable(stuff)
False
pprint.isrecursive(object)
object が再帰的表現を必要とするかどうかを判別します。

もう1つのサポート関数も定義されています。

pprint.saferepr(object)

再帰的なデータ構造から保護されたオブジェクトの文字列表現を返します。 オブジェクトの表現が再帰エントリを公開する場合、再帰参照は<Recursion on typename with id=number>として表されます。 表現は他の方法でフォーマットされていません。

>>> pprint.saferepr(stuff)
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"

PrettyPrinterオブジェクト

PrettyPrinter インスタンスには次のメソッドがあります。

PrettyPrinter.pformat(object)
オブジェクトのフォーマットされた表現を返します。 これは、 PrettyPrinter コンストラクターに渡されるオプションを考慮に入れています。
PrettyPrinter.pprint(object)
構成されたストリームにオブジェクトのフォーマットされた表現を出力し、その後に改行を続けます。

次のメソッドは、同じ名前の対応する関数の実装を提供します。 新しい PrettyPrinter オブジェクトを作成する必要がないため、インスタンスでこれらのメソッドを使用する方が少し効率的です。

PrettyPrinter.isreadable(object)
オブジェクトのフォーマットされた表現が「読み取り可能」であるかどうか、または eval()を使用して値を再構築するために使用できるかどうかを判別します。 これにより、再帰オブジェクトに対してFalseが返されることに注意してください。 PrettyPrinterdepth パラメーターが設定されていて、オブジェクトが許可されているよりも深い場合、Falseが返されます。
PrettyPrinter.isrecursive(object)
オブジェクトが再帰的表現を必要とするかどうかを判別します。

このメソッドは、サブクラスがオブジェクトを文字列に変換する方法を変更できるようにするためのフックとして提供されています。 デフォルトの実装は、 saferepr()実装の内部を使用します。

PrettyPrinter.format(object, context, maxlevels, level)
文字列としての object のフォーマットされたバージョン、結果が読み取り可能かどうかを示すフラグ、および再帰が検出されたかどうかを示すフラグの3つの値を返します。 最初の引数は、提示されるオブジェクトです。 2つ目は、現在のプレゼンテーションコンテキストの一部であるオブジェクト(プレゼンテーションに影響を与えるオブジェクトの直接および間接コンテナ)の id()をキーとして含む辞書です。 context ですでに表されているオブジェクトを提示する必要がある場合、3番目の戻り値はTrueである必要があります。 format()メソッドを再帰的に呼び出すと、このディクショナリにコンテナのエントリが追加されます。 3番目の引数 maxlevels は、要求された再帰の制限を示します。 要求された制限がない場合、これは0になります。 この引数は、変更せずに再帰呼び出しに渡す必要があります。 4番目の引数 level は、現在のレベルを示します。 再帰呼び出しには、現在の呼び出しよりも小さい値を渡す必要があります。


pprint()関数とそのパラメーターのいくつかの使用法を示すために、 PyPI からプロジェクトに関する情報を取得してみましょう。

>>> import json
>>> import pprint
>>> from urllib.request import urlopen
>>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
...     project_info = json.load(resp)['info']

基本的な形式では、 pprint()はオブジェクト全体を示しています。

>>> pprint.pprint(project_info)
{'author': 'The Python Packaging Authority',
 'author_email': '[email protected]',
 'bugtrack_url': None,
 'classifiers': ['Development Status :: 3 - Alpha',
                 'Intended Audience :: Developers',
                 'License :: OSI Approved :: MIT License',
                 'Programming Language :: Python :: 2',
                 'Programming Language :: Python :: 2.6',
                 'Programming Language :: Python :: 2.7',
                 'Programming Language :: Python :: 3',
                 'Programming Language :: Python :: 3.2',
                 'Programming Language :: Python :: 3.3',
                 'Programming Language :: Python :: 3.4',
                 'Topic :: Software Development :: Build Tools'],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and be written using '
                'ReStructured Text. It\n'
                'will be used to generate the project webpage on PyPI, and '
                'should be written for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not\n'
                'a good idea, although a simple "What\'s New" section for the '
                'most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': {'Download': 'UNKNOWN',
                  'Homepage': 'https://github.com/pypa/sampleproject'},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'}

結果は特定の depth に制限できます(省略記号はより深いコンテンツに使用されます)。

>>> pprint.pprint(project_info, depth=1)
{'author': 'The Python Packaging Authority',
 'author_email': '[email protected]',
 'bugtrack_url': None,
 'classifiers': [...],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and be written using '
                'ReStructured Text. It\n'
                'will be used to generate the project webpage on PyPI, and '
                'should be written for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not\n'
                'a good idea, although a simple "What\'s New" section for the '
                'most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': {...},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': {...},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'}

さらに、最大文字数を提案できます。 長いオブジェクトを分割できない場合、指定された幅を超えます。

>>> pprint.pprint(project_info, depth=1, width=60)
{'author': 'The Python Packaging Authority',
 'author_email': '[email protected]',
 'bugtrack_url': None,
 'classifiers': [...],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the '
                'project.\n'
                '\n'
                'The file should use UTF-8 encoding and be '
                'written using ReStructured Text. It\n'
                'will be used to generate the project '
                'webpage on PyPI, and should be written '
                'for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would '
                'include an overview of the project, '
                'basic\n'
                'usage examples, etc. Generally, including '
                'the project changelog in here is not\n'
                'a good idea, although a simple "What\'s '
                'New" section for the most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': {...},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': {...},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'}