diff --git a/Lib/pprint.py b/Lib/pprint.py --- a/Lib/pprint.py +++ b/Lib/pprint.py @@ -28,6 +28,10 @@ pformat() pprint() Pretty-print a Python object to a stream [default is sys.stdout]. +print() + Pretty-print Python objects to a stream; signature is compatible with + built-in print, to allow drop-in replacement. + saferepr() Generate a 'standard' repr()-like value, but protect against recursive data structures. @@ -38,8 +42,8 @@ import sys as _sys from collections import OrderedDict as _OrderedDict from io import StringIO as _StringIO -__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr", - "PrettyPrinter"] +__all__ = ["pprint", "pformat", "print", "isreadable", "isrecursive", + "saferepr", "PrettyPrinter"] # cache these for faster access: _commajoin = ", ".join @@ -54,6 +58,10 @@ def pprint(object, stream=None, indent=1 stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object) +def print(*values, sep=' ', end='\n', file=None): + """Pretty-print values to a stream (print drop-in).""" + PrettyPrinter().print(*values, sep=sep, end=end, file=file) + def pformat(object, indent=1, width=80, depth=None): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object) @@ -132,6 +140,33 @@ class PrettyPrinter: self._format(object, self._stream, 0, 0, {}, 0) self._stream.write("\n") + def print(self, *values, sep=',\n', end='\n', file=None): + r"""Pretty-print values to a stream (print drop-in). + + Optional keyword arguments: + file: a file-like object (stream); if None, defaults to the stream + passed to the constructor (which defaults to sys.stdout) + sep: string inserted between values, defaults to ',\n'. + end: string appended after the last value, defaults to '\n'. + """ + if file is None: + file = self._stream + + values = iter(values) + try: + value = next(values) + except StopIteration: + # iterator of length 0 + file.write(end) + return + + self._format(value, file, 0, 0, {}, 0) + + for value in values: + file.write(sep) + self._format(value, file, 0, 0, {}, 0) + file.write(end) + def pformat(self, object): sio = _StringIO() self._format(object, sio, 0, 0, {}, 0)