Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 16 additions & 15 deletions Doc/library/pprint.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Functions
---------

.. function:: pp(object, stream=None, indent=1, width=80, depth=None, *, \
block_style=False, compact=False, sort_dicts=False, \
compact=False, expand=False, sort_dicts=False, \
underscore_numbers=False)

Prints the formatted representation of *object*, followed by a newline.
Expand Down Expand Up @@ -75,6 +75,13 @@ Functions
each item of a sequence will be formatted on a separate line,
otherwise as many items as will fit within the *width*
will be formatted on each output line.
Incompatible with *expand*.

:param bool expand:
If ``True``,
opening parentheses and brackets will be followed by a newline and the
following content will be indented by one level, similar to block style
JSON formatting. Incompatible with *compact*.

:param bool sort_dicts:
If ``True``, dictionaries will be formatted with
Expand All @@ -86,12 +93,6 @@ Functions
integers will be formatted with the ``_`` character for a thousands separator,
otherwise underscores are not displayed (the default).

:param bool block_style:
If ``True``,
opening parentheses and brackets will be followed by a newline and the
following content will be indented by one level, similar to block style
JSON formatting. This option is not compatible with *compact*.

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff)
Expand All @@ -107,7 +108,7 @@ Functions


.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \
block_style=False, compact=False, sort_dicts=True, \
compact=False, expand=False, sort_dicts=True, \
underscore_numbers=False)

Alias for :func:`~pprint.pp` with *sort_dicts* set to ``True`` by default,
Expand All @@ -116,11 +117,11 @@ Functions


.. function:: pformat(object, indent=1, width=80, depth=None, *, \
block_style=False, compact=False, sort_dicts=True, \
compact=False, expand=False, sort_dicts=True, \
underscore_numbers=False)

Return the formatted representation of *object* as a string. *indent*,
*width*, *depth*, *compact*, *sort_dicts*, *underscore_numbers* and *block_style* are
*width*, *depth*, *compact*, *expand*, *sort_dicts* and *underscore_numbers* are
passed to the :class:`PrettyPrinter` constructor as formatting parameters
and their meanings are as described in the documentation above.

Expand Down Expand Up @@ -164,7 +165,7 @@ PrettyPrinter Objects
.. index:: single: ...; placeholder

.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \
block_style=False, compact=False, sort_dicts=True, \
compact=False, expand=False, sort_dicts=True, \
underscore_numbers=False)

Construct a :class:`PrettyPrinter` instance.
Expand All @@ -189,7 +190,7 @@ PrettyPrinter Objects
'knights', 'ni'],
'spam', 'eggs', 'lumberjack', 'knights',
'ni']
>>> pp = pprint.PrettyPrinter(width=41, block_style=True, indent=3)
>>> pp = pprint.PrettyPrinter(width=41, expand=True, indent=3)
>>> pp.pprint(stuff)
[
[
Expand Down Expand Up @@ -225,7 +226,7 @@ PrettyPrinter Objects
No longer attempts to write to :data:`!sys.stdout` if it is ``None``.

.. versionchanged:: next
Added the *block_style* parameter.
Added the *expand* parameter.


:class:`PrettyPrinter` instances have the following methods:
Expand Down Expand Up @@ -450,10 +451,10 @@ cannot be split, the specified width will be exceeded::
'summary': 'A sample Python project',
'version': '1.2.0'}

Lastly, we can achieve block style formatting with the *block_style* parameter.
Lastly, we can achieve block style formatting with the *expand* parameter.
Best results are achieved with a higher *indent* value::

>>> pprint.pp(project_info, indent=4, block_style=True)
>>> pprint.pp(project_info, indent=4, expand=True)
{
'author': 'The Python Packaging Authority',
'author_email': 'pypa-dev@googlegroups.com',
Expand Down
2 changes: 1 addition & 1 deletion Doc/whatsnew/3.15.rst
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ platform
pprint
------

* Add a *block_style* keyword argument for :func:`pprint.pprint`,
* Add an *expand* keyword argument for :func:`pprint.pprint`,
:func:`pprint.pformat`, :func:`pprint.pp`. If true, the output will be
formatted in a block style similar to pretty-printed :func:`json.dumps` when
*indent* is supplied.
Expand Down
76 changes: 38 additions & 38 deletions Lib/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,24 +44,23 @@


def pprint(object, stream=None, indent=1, width=80, depth=None, *,
block_style=False, compact=False, sort_dicts=True,
compact=False, expand=False, sort_dicts=True,
underscore_numbers=False):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth,
compact=compact, sort_dicts=sort_dicts,
underscore_numbers=underscore_numbers, block_style=block_style)
compact=compact, expand=expand, sort_dicts=sort_dicts,
underscore_numbers=underscore_numbers)
printer.pprint(object)


def pformat(object, indent=1, width=80, depth=None, *,
block_style=False, compact=False, sort_dicts=True,
compact=False, expand=False, sort_dicts=True,
underscore_numbers=False):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth,
compact=compact, sort_dicts=sort_dicts,
underscore_numbers=underscore_numbers,
block_style=block_style).pformat(object)
compact=compact, expand=expand, sort_dicts=sort_dicts,
underscore_numbers=underscore_numbers).pformat(object)


def pp(object, *args, sort_dicts=False, **kwargs):
Expand Down Expand Up @@ -114,7 +113,7 @@ def _safe_tuple(t):

class PrettyPrinter:
def __init__(self, indent=1, width=80, depth=None, stream=None, *,
block_style=False, compact=False, sort_dicts=True,
compact=False, expand=False, sort_dicts=True,
underscore_numbers=False):
"""Handle pretty printing operations onto a stream using a set of
configured parameters.
Expand All @@ -134,18 +133,19 @@ def __init__(self, indent=1, width=80, depth=None, stream=None, *,

compact
If true, several items will be combined in one line.
Incompatible with expand mode.

expand
If true, the output will be formatted in a block style similar to
pretty-printed json.dumps() when ``indent`` is supplied.
Incompatible with compact mode.

sort_dicts
If true, dict keys are sorted.

underscore_numbers
If true, digit groups are separated with underscores.

block_style
If true, the output will be formatted in a block style similar to
pretty-printed json.dumps() when ``indent`` is supplied.
Incompatible with compact mode.

"""
indent = int(indent)
width = int(width)
Expand All @@ -155,8 +155,8 @@ def __init__(self, indent=1, width=80, depth=None, stream=None, *,
raise ValueError('depth must be > 0')
if not width:
raise ValueError('width must be != 0')
if compact and block_style:
raise ValueError('compact and block_style are incompatible')
if compact and expand:
raise ValueError('compact and expand are incompatible')
self._depth = depth
self._indent_per_level = indent
self._width = width
Expand All @@ -165,9 +165,9 @@ def __init__(self, indent=1, width=80, depth=None, stream=None, *,
else:
self._stream = _sys.stdout
self._compact = bool(compact)
self._expand = bool(expand)
self._sort_dicts = sort_dicts
self._underscore_numbers = underscore_numbers
self._block_style = bool(block_style)

def pprint(self, object):
if self._stream is not None:
Expand Down Expand Up @@ -218,12 +218,12 @@ def _format(self, object, stream, indent, allowance, context, level):
stream.write(rep)

def _format_block_start(self, start_str, indent):
if self._block_style:
if self._expand:
return f"{start_str}\n{' ' * indent}"
return start_str

def _format_block_end(self, end_str, indent):
if self._block_style:
if self._expand:
return f"\n{' ' * indent}{end_str}"
return end_str

Expand All @@ -232,7 +232,7 @@ def _pprint_dataclass(self, object, stream, indent, allowance, context, level):
from dataclasses import fields as dataclass_fields

cls_name = object.__class__.__name__
if self._block_style:
if self._expand:
indent += self._indent_per_level
else:
indent += len(cls_name) + 1
Expand All @@ -246,9 +246,9 @@ def _pprint_dataclass(self, object, stream, indent, allowance, context, level):
def _pprint_dict(self, object, stream, indent, allowance, context, level):
write = stream.write
write(self._format_block_start('{', indent))
if self._indent_per_level > 1 and not self._block_style:
if self._indent_per_level > 1 and not self._expand:
write((self._indent_per_level - 1) * ' ')
if self._indent_per_level > 0 and self._block_style:
if self._indent_per_level > 0 and self._expand:
write(self._indent_per_level * ' ')
length = len(object)
if length:
Expand All @@ -268,7 +268,7 @@ def _pprint_ordered_dict(self, object, stream, indent, allowance, context, level
return
cls = object.__class__
stream.write(cls.__name__ + '(')
if self._block_style:
if self._expand:
recursive_indent = indent
else:
recursive_indent = indent + len(cls.__name__) + 1
Expand Down Expand Up @@ -349,7 +349,7 @@ def _pprint_set(self, object, stream, indent, allowance, context, level):
else:
stream.write(self._format_block_start(typ.__name__ + '({', indent))
endchar = '})'
if not self._block_style:
if not self._expand:
indent += len(typ.__name__) + 1
object = sorted(object, key=_safe_key)
self._format_items(object, stream, indent, allowance + len(endchar),
Expand Down Expand Up @@ -420,7 +420,7 @@ def _pprint_bytes(self, object, stream, indent, allowance, context, level):
return
parens = level == 1
if parens:
if self._block_style:
if self._expand:
indent += self._indent_per_level
else:
indent += 1
Expand All @@ -440,7 +440,7 @@ def _pprint_bytes(self, object, stream, indent, allowance, context, level):
def _pprint_bytearray(self, object, stream, indent, allowance, context, level):
write = stream.write
write(self._format_block_start('bytearray(', indent))
if self._block_style:
if self._expand:
write(' ' * self._indent_per_level)
recursive_indent = indent + self._indent_per_level
else:
Expand All @@ -453,7 +453,7 @@ def _pprint_bytearray(self, object, stream, indent, allowance, context, level):

def _pprint_mappingproxy(self, object, stream, indent, allowance, context, level):
stream.write('mappingproxy(')
if self._block_style:
if self._expand:
recursive_indent = indent
else:
recursive_indent = indent + 13
Expand All @@ -470,7 +470,7 @@ def _pprint_simplenamespace(self, object, stream, indent, allowance, context, le
cls_name = 'namespace'
else:
cls_name = object.__class__.__name__
if self._block_style:
if self._expand:
indent += self._indent_per_level
else:
indent += len(cls_name) + 1
Expand All @@ -493,7 +493,7 @@ def _format_dict_items(self, items, stream, indent, allowance, context,
rep = self._repr(key, context, level)
write(rep)
write(': ')
if self._block_style:
if self._expand:
recursive_indent = indent
else:
recursive_indent = indent + len(rep) + 2
Expand All @@ -516,7 +516,7 @@ def _format_namespace_items(self, items, stream, indent, allowance, context, lev
# recursive dataclass repr.
write("...")
else:
if self._block_style:
if self._expand:
recursive_indent = indent
else:
recursive_indent = indent + len(key) + 1
Expand All @@ -529,9 +529,9 @@ def _format_namespace_items(self, items, stream, indent, allowance, context, lev
def _format_items(self, items, stream, indent, allowance, context, level):
write = stream.write
indent += self._indent_per_level
if self._indent_per_level > 1 and not self._block_style:
if self._indent_per_level > 1 and not self._expand:
write((self._indent_per_level - 1) * ' ')
if self._indent_per_level > 0 and self._block_style:
if self._indent_per_level > 0 and self._expand:
write(self._indent_per_level * ' ')
delimnl = ',\n' + ' ' * indent
delim = ''
Expand Down Expand Up @@ -591,7 +591,7 @@ def _pprint_default_dict(self, object, stream, indent, allowance, context, level
return
rdf = self._repr(object.default_factory, context, level)
cls = object.__class__
if self._block_style:
if self._expand:
stream.write('%s(%s, ' % (cls.__name__, rdf))
else:
indent += len(cls.__name__) + 1
Expand All @@ -608,12 +608,12 @@ def _pprint_counter(self, object, stream, indent, allowance, context, level):
return
cls = object.__class__
stream.write(self._format_block_start(cls.__name__ + '({', indent))
if self._indent_per_level > 1 and not self._block_style:
if self._indent_per_level > 1 and not self._expand:
stream.write((self._indent_per_level - 1) * ' ')
if self._indent_per_level > 0 and self._block_style:
if self._indent_per_level > 0 and self._expand:
stream.write(self._indent_per_level * ' ')
items = object.most_common()
if self._block_style:
if self._expand:
recursive_indent = indent
else:
recursive_indent = indent + len(cls.__name__) + 1
Expand All @@ -630,7 +630,7 @@ def _pprint_chain_map(self, object, stream, indent, allowance, context, level):
cls = object.__class__
stream.write(self._format_block_start(cls.__name__ + '(',
indent + self._indent_per_level))
if self._block_style:
if self._expand:
indent += self._indent_per_level
else:
indent += len(cls.__name__) + 1
Expand All @@ -650,7 +650,7 @@ def _pprint_deque(self, object, stream, indent, allowance, context, level):
return
cls = object.__class__
stream.write(self._format_block_start(cls.__name__ + '([', indent))
if not self._block_style:
if not self._expand:
indent += len(cls.__name__) + 1
if object.maxlen is None:
self._format_items(object, stream, indent, allowance + 2,
Expand All @@ -660,7 +660,7 @@ def _pprint_deque(self, object, stream, indent, allowance, context, level):
self._format_items(object, stream, indent, 2,
context, level)
rml = self._repr(object.maxlen, context, level)
if self._block_style:
if self._expand:
stream.write('%s], maxlen=%s)' % ('\n' + ' ' * indent, rml))
else:
stream.write('],\n%smaxlen=%s)' % (' ' * indent, rml))
Expand Down
Loading
Loading