pprint
— Data pretty printer数据漂亮打印机¶
Source code: Lib/pprint.py
The pprint
module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. pprint
模块提供了以可作为解释器输入的形式“漂亮地打印”任意Python数据结构的能力。If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. 如果格式化结构包含非基本Python类型的对象,则表示可能无法加载。This may be the case if objects such as files, sockets or classes are included, as well as many other objects which are not representable as Python literals.如果包含文件、套接字或类等对象,以及许多其他不能表示为Python文字的对象,则可能会出现这种情况。
The formatted representation keeps objects on a single line if it can, and breaks them onto multiple lines if they don’t fit within the allowed width. 格式化表示法可以将对象保留在一行上,如果不在允许的宽度内,则将其拆分为多行。Construct 如果需要调整宽度约束,请显式构造PrettyPrinter
objects explicitly if you need to adjust the width constraint.PrettyPrinter
对象。
Dictionaries are sorted by key before the display is computed.在计算显示之前,字典按键排序。
Changed in version 3.9:版本3.9中更改: Added support for pretty-printing 添加了对漂亮打印types.SimpleNamespace
.types.SimpleNamespace
的支持。
Changed in version 3.10:版本3.10中更改: Added support for pretty-printing 添加了对漂亮打印dataclasses.dataclass
.dataclasses.dataclass
的支持。
The pprint
module defines one class:pprint
模块定义了一个类:
-
class
pprint.
PrettyPrinter
(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True, underscore_numbers=False)¶ Construct a构造PrettyPrinter
instance.PrettyPrinter
实例。This constructor understands several keyword parameters.此构造函数了解几个关键字参数。stream (defaultstream(默认sys.stdout
) is a file-like object to which the output will be written by calling itswrite()
method.sys.stdout
)是一个类似文件的对象,通过调用其write()
方法将输出写入该对象。Other values configure the manner in which nesting of complex data structures is displayed.其他值配置复杂数据结构嵌套的显示方式。indent
(default 1) specifies the amount of indentation added for each nesting level.(默认值1)指定为每个嵌套级别添加的缩进量。depth
controls the number of nesting levels which may be printed; if the data structure being printed is too deep, the next contained level is replaced by控制可以打印的嵌套级别的数量;如果打印的数据结构太深,则下一个包含的级别将替换为...
....
。By default, there is no constraint on the depth of the objects being formatted.默认情况下,对正在格式化的对象的深度没有约束。width (default 80) specifies the desired maximum number of characters per line in the output.width(默认值80)指定输出中每行所需的最大字符数。If a structure cannot be formatted within the width constraint, a best effort will be made.如果无法在宽度约束内格式化结构,将尽最大努力。compact impacts the way that long sequences (lists, tuples, sets, etc) are formatted.compact影响长序列(列表、元组、集等)的格式。If compact is false (the default) then each item of a sequence will be formatted on a separate line.如果compact为false
(默认值),则序列的每个项目都将在单独的行上格式化。If compact is true, as many items as will fit within the width will be formatted on each output line.如果compact为true
,则将在每个输出行上格式化width范围内的尽可能多的项目。If sort_dicts is true (the default), dictionaries will be formatted with their keys sorted, otherwise they will display in insertion order.如果sort_dicts为true
(默认值),则字典将使用已排序的键进行格式化,否则将按插入顺序显示。If underscore_numbers is true, integers will be formatted with the如果underline_numbers为_
character for a thousands separator, otherwise underscores are not displayed (the default).true
,则整数的格式将使用_
字符作为千位分隔符,否则不显示下划线(默认设置)。Changed in version 3.4:版本3.4中更改:Added the compact parameter.添加了compact参数。Changed in version 3.8:版本3.8中更改:Added the sort_dicts parameter.添加了sort_dicts参数。Changed in version 3.10:版本3.10中更改:Added the underscore_numbers parameter.添加了underscore_numbers参数。>>> 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', (...)))))))
The pprint
module also provides several shortcut functions:pprint
模块还提供了几个快捷功能:
-
pprint.
pformat
(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)¶ Return the formatted representation of object as a string.以字符串形式返回object的格式化表示。indent, width, depth, compact, sort_dicts and underscore_numbers will be passed to theindent、width、depth、compact、sort_dicts和underscore_numbers将作为格式化参数传递给PrettyPrinter
constructor as formatting parameters.PrettyPrinter
构造函数。Changed in version 3.4:版本3.4中更改:Added the compact parameter.添加了compact参数。Changed in version 3.8:版本3.8中更改:Added the sort_dicts parameter.添加了sort_dicts参数。Changed in version 3.10:版本3.10中更改:Added the underscore_numbers parameter.添加了underscore_numbers参数。
-
pprint.
pp
(object, *args, sort_dicts=False, **kwargs)¶ Prints the formatted representation of object followed by a newline.打印object的格式化表示,后跟换行符。If sort_dicts is false (the default), dictionaries will be displayed with their keys in insertion order, otherwise the dict keys will be sorted.如果sort_dicts为false
(默认值),字典将按插入顺序显示其键,否则将对dict键进行排序。args and kwargs will be passed toargs和kwargs将作为格式化参数传递给pprint()
as formatting parameters.pprint()
。New in version 3.8.版本3.8中新增。
-
pprint.
pprint
(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)¶ Prints the formatted representation of object on stream, followed by a newline.打印stream上object的格式化表示,后跟换行符。If stream is如果stream为None
,sys.stdout
is used.None
,则使用sys.stdout
。This may be used in the interactive interpreter instead of the这可以在交互式解释器中使用,而不是在print()
function for inspecting values (you can even reassignprint = pprint.pprint
for use within a scope).print()
函数中检查值(您甚至可以重新指定print = pprint.pprint
以在范围内使用)。indent, width, depth, compact, sort_dicts and underscore_numbers will be passed to theindent、width、depth、compact、sort_dicts和underscore_numbers将作为格式化参数传递给PrettyPrinter构造函数。PrettyPrinter
constructor as formatting parameters.Changed in version 3.4:版本3.4中更改:Added the compact parameter.添加了compact参数。Changed in version 3.8:版本3.8中更改:Added the sort_dicts parameter.添加了sort_dicts参数。Changed in version 3.10:版本3.10中更改:Added the underscore_numbers parameter.添加了underscore_numbers参数。>>> 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)¶ -
Determine if the formatted representation of object is “readable”, or can be used to reconstruct the value using确定object的格式化表示是“可读的”,还是可以使用eval()
.eval()
重建值。This always returns对于递归对象,这总是返回False
for recursive objects.False
。>>> pprint.isreadable(stuff)
False
-
pprint.
isrecursive
(object)¶ Determine if object requires a recursive representation.确定object是否需要递归表示。
One more support function is also defined:还定义了另一个支持函数:
-
pprint.
saferepr
(object)¶ Return a string representation of object, protected against recursive data structures.返回object的字符串表示形式,防止递归数据结构。If the representation of object exposes a recursive entry, the recursive reference will be represented as如果object的表示公开了递归条目,则递归引用将表示为<Recursion on typename with id=number>
.<Recursion on typename with id=number>
。The representation is not otherwise formatted.表示形式没有其他格式。>>> pprint.saferepr(stuff)
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
PrettyPrinter
Objects对象¶
PrettyPrinter
instances have the following methods:实例有以下方法:
-
PrettyPrinter.
pformat
(object)¶ Return the formatted representation of object.返回object的格式化表示。This takes into account the options passed to the这考虑了传递给PrettyPrinter
constructor.PrettyPrinter
构造函数的选项。
-
PrettyPrinter.
pprint
(object)¶ Print the formatted representation of object on the configured stream, followed by a newline.在配置的流上打印object的格式化表示,后跟换行符。
The following methods provide the implementations for the corresponding functions of the same names. 以下方法提供了同名对应函数的实现。Using these methods on an instance is slightly more efficient since new 由于不需要创建新的PrettyPrinter
objects don’t need to be created.PrettyPrinter
对象,因此在实例上使用这些方法效率略高。
-
PrettyPrinter.
isreadable
(object)¶ -
Determine if the formatted representation of the object is “readable,” or can be used to reconstruct the value using确定对象的格式化表示是“可读的”,还是可以使用eval()
.eval()
重建值。Note that this returns注意,对于递归对象,这将返回False
for recursive objects.False
。If the depth parameter of the如果设置了PrettyPrinter
is set and the object is deeper than allowed, this returnsFalse
.PrettyPrinter
的depth参数,并且对象深度超过允许深度,则返回False
。
-
PrettyPrinter.
isrecursive
(object)¶ Determine if the object requires a recursive representation.确定对象是否需要递归表示。
This method is provided as a hook to allow subclasses to modify the way objects are converted to strings. 该方法作为钩子提供,允许子类修改将对象转换为字符串的方式。The default implementation uses the internals of the 默认实现使用saferepr()
implementation.saferepr()
实现的内部。
-
PrettyPrinter.
format
(object, context, maxlevels, level)¶ Returns three values: the formatted version of object as a string, a flag indicating whether the result is readable, and a flag indicating whether recursion was detected.返回三个值:作为字符串的object的格式化版本、指示结果是否可读的标志和指示是否检测到递归的标志。The first argument is the object to be presented.第一个参数是要呈现的对象。The second is a dictionary which contains the第二个是字典,其中包含作为当前表示上下文一部分的对象的id()
of objects that are part of the current presentation context (direct and indirect containers for object that are affecting the presentation) as the keys; if an object needs to be presented which is already represented in context, the third return value should beTrue
.id()
(影响表示的object的直接和间接容器)作为键;如果需要呈现已经在context中表示的对象,则第三个返回值应为True
。Recursive calls to the对format()
method should add additional entries for containers to this dictionary.format()
方法的递归调用应将容器的其他条目添加到此字典中。The third argument, maxlevels, gives the requested limit to recursion; this will be第三个参数maxlevels给出了递归的请求限制;如果没有请求的限制,则该值将为0
if there is no requested limit.0
。This argument should be passed unmodified to recursive calls.此参数应未经修改地传递给递归调用。The fourth argument, level, gives the current level; recursive calls should be passed a value less than that of the current call.第四个参数,level,给出了当前级别;递归调用传递的值应小于当前调用的值。
Example示例¶
To demonstrate several uses of the 为了演示pprint()
function and its parameters, let’s fetch information about a project from PyPI: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']
In its basic form, 在其基本形式中,pprint()
shows the whole object:pprint()
显示了整个对象:
>>> pprint.pprint(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.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'}
The result can be limited to a certain depth (ellipsis is used for deeper contents):结果可以限制在一定的depth(省略号用于更深入的内容):
>>> pprint.pprint(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.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'}
Additionally, maximum character width can be suggested. 此外,可以建议最大字符width。If a long object cannot be split, the specified width will be exceeded:如果无法分割长对象,则将超过指定的宽度:
>>> pprint.pprint(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.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'}