pprint
— 数据美化打印机¶
源代码: Lib/pprint.py
pprint
模块提供了“美化打印”任意 Python 数据结构的功能,其输出形式可以作为解释器的输入。如果格式化的结构包含非 Python 基本类型的对象,则表示可能无法加载。例如,如果包含文件、套接字或类等对象,以及许多其他不能表示为 Python 字面量的对象,就可能出现这种情况。
格式化表示会尽可能将对象保持在一行中,如果超出了允许的宽度,则会将其分拆成多行,宽度可通过 width 参数调整,默认为 80 个字符。
3.9 版本中有所改变: 新增了对美化打印 types.SimpleNamespace
的支持。
3.10 版本中有所改变: 新增了对美化打印 dataclasses.dataclass
的支持。
函数¶
- pprint.pp(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=False, underscore_numbers=False)¶
打印 object 的格式化表示,后跟一个换行符。此函数可以在交互式解释器中用于检查值,代替
print()
函数。提示:您可以将print = pprint.pp
重新赋值以在某个作用域内使用。- 参数:
object – 要打印的对象。
stream (类文件对象 | None) – 一个类文件对象,输出将通过调用其
write()
方法写入到该对象。如果为None
(默认值),则使用sys.stdout
。indent (int) – 每个嵌套级别添加的缩进量。
width (int) – 输出中每行所需的最大字符数。如果结构无法在宽度限制内格式化,将尽力而为。
depth (int | None) – 可以打印的嵌套级别数。如果要打印的数据结构过深,下一个包含的级别将替换为
...
。如果为None
(默认值),则对要格式化对象的深度没有限制。compact (bool) – 控制长序列的格式化方式。如果为
False
(默认值),序列的每个项目将格式化为单独一行,否则在 width 内能容纳的项目将格式化为每行。sort_dicts (bool) – 如果为
True
,字典将按键排序格式化,否则按插入顺序显示(默认值)。underscore_numbers (bool) – 如果为
True
,整数将以_
字符作为千位分隔符进行格式化,否则不显示下划线(默认值)。
>>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff) >>> pprint.pp(stuff) [<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']
在 3.8 版本加入。
- pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)¶
pp()
的别名,默认将 sort_dicts 设置为True
,这会自动对字典的键进行排序。您可能更希望使用默认值为False
的pp()
。
- pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)¶
将 object 的格式化表示作为字符串返回。indent、width、depth、compact、sort_dicts 和 underscore_numbers 作为格式化参数传递给
PrettyPrinter
构造函数,其含义如上文文档所述。
- pprint.isreadable(object)¶
确定 object 的格式化表示是否“可读”,或者是否可以使用
eval()
来重建其值。对于递归对象,此函数始终返回False
。>>> pprint.isreadable(stuff) False
- pprint.isrecursive(object)¶
确定 object 是否需要递归表示。此函数受限于下文
saferepr()
中所述的相同限制,如果未能检测到递归对象,可能会引发RecursionError
。
PrettyPrinter 对象¶
- class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True, underscore_numbers=False)¶
构造一个
PrettyPrinter
实例。参数的含义与
pp()
相同。请注意,它们的顺序不同,并且 sort_dicts 默认值为True
。>>> 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', (...)))))))
3.4 版本中有所改变: 添加了 compact 参数。
3.8 版本中有所改变: 添加了 sort_dicts 参数。
3.10 版本中有所改变: 添加了 underscore_numbers 参数。
3.11 版本中有所改变: 如果
sys.stdout
为None
,则不再尝试写入。
PrettyPrinter
实例具有以下方法
- PrettyPrinter.pformat(object)¶
返回 object 的格式化表示。这会考虑传递给
PrettyPrinter
构造函数的选项。
- PrettyPrinter.pprint(object)¶
在配置的流上打印 object 的格式化表示,后跟一个换行符。
以下方法提供了同名对应函数的实现。在实例上使用这些方法效率略高,因为无需创建新的 PrettyPrinter
对象。
- PrettyPrinter.isreadable(object)¶
确定对象的格式化表示是否“可读”,或者是否可以使用
eval()
来重建其值。请注意,对于递归对象,此函数返回False
。如果设置了PrettyPrinter
的 depth 参数并且对象深度超过允许值,则此函数返回False
。
- PrettyPrinter.isrecursive(object)¶
确定对象是否需要递归表示。
此方法作为钩子提供,允许子类修改对象转换为字符串的方式。默认实现使用 saferepr()
实现的内部机制。
- PrettyPrinter.format(object, context, maxlevels, level)¶
返回三个值:object 的格式化版本(字符串),一个指示结果是否可读的标志,以及一个指示是否检测到递归的标志。第一个参数是要呈现的对象。第二个是一个字典,其中包含作为键的当前呈现上下文(直接和间接容器,它们影响着 object 的呈现)中对象的
id()
;如果需要呈现的对象已在 context 中表示,则第三个返回值应为True
。对format()
方法的递归调用应为此字典添加更多容器条目。第三个参数 maxlevels 给出了请求的递归限制;如果没有请求限制,则为0
。此参数应未经修改地传递给递归调用。第四个参数 level 给出了当前级别;递归调用应传递一个小于当前调用值的值。
示例¶
为了演示 pp()
函数及其参数的多种用法,让我们从 PyPI 获取一个项目的信息
>>> import json
>>> import pprint
>>> from urllib.request import urlopen
>>> with urlopen('https://pypi.ac.cn/pypi/sampleproject/1.2.0/json') as resp:
... project_info = json.load(resp)['info']
在其基本形式中,pp()
显示整个对象
>>> pprint.pp(project_info)
{'author': 'The Python Packaging Authority',
'author_email': 'pypa-dev@googlegroups.com',
'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.ac.cn/project/sampleproject/',
'platform': 'UNKNOWN',
'project_url': 'https://pypi.ac.cn/project/sampleproject/',
'project_urls': {'Download': 'UNKNOWN',
'Homepage': 'https://github.com/pypa/sampleproject'},
'release_url': 'https://pypi.ac.cn/project/sampleproject/1.2.0/',
'requires_dist': None,
'requires_python': None,
'summary': 'A sample Python project',
'version': '1.2.0'}
结果可以限制在某个 depth 内(更深的内容使用省略号表示)
>>> pprint.pp(project_info, depth=1)
{'author': 'The Python Packaging Authority',
'author_email': 'pypa-dev@googlegroups.com',
'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.ac.cn/project/sampleproject/',
'platform': 'UNKNOWN',
'project_url': 'https://pypi.ac.cn/project/sampleproject/',
'project_urls': {...},
'release_url': 'https://pypi.ac.cn/project/sampleproject/1.2.0/',
'requires_dist': None,
'requires_python': None,
'summary': 'A sample Python project',
'version': '1.2.0'}
此外,可以建议最大字符 width。如果长对象无法拆分,则会超出指定的宽度
>>> pprint.pp(project_info, depth=1, width=60)
{'author': 'The Python Packaging Authority',
'author_email': 'pypa-dev@googlegroups.com',
'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.ac.cn/project/sampleproject/',
'platform': 'UNKNOWN',
'project_url': 'https://pypi.ac.cn/project/sampleproject/',
'project_urls': {...},
'release_url': 'https://pypi.ac.cn/project/sampleproject/1.2.0/',
'requires_dist': None,
'requires_python': None,
'summary': 'A sample Python project',
'version': '1.2.0'}