-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
PEP 813: The Pretty Print Protocol #4690
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
warsaw
wants to merge
19
commits into
python:main
Choose a base branch
from
warsaw:pep-813-pprint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+245
−1
Open
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
398f467
PEP 813: The Pretty Print Protocol
warsaw 25c70f7
The Elder Statesmen of Python
warsaw 5555617
Fix markup errors
warsaw cd0a257
One more linting bug
warsaw 1d4b9d1
Exmaple fixes
warsaw b8fc7e4
Alone again, naturally
warsaw 263a95b
Update peps/pep-0813.rst
warsaw 143cb6c
The dunder is __pprint__(), not __pretty__()
warsaw a8598f7
Update peps/pep-0813.rst
warsaw 1a96c8d
Merge branch 'pep-813-pprint' of github.com:warsaw/peps into pep-813-…
warsaw 2703f5c
Update based on @AA-Turner's feedback
warsaw 686fc4d
Update peps/pep-0813.rst
warsaw 94d20f5
Merge branch 'main' into pep-813-pprint
warsaw 1cf369c
Merge branch 'main' into pep-813-pprint
warsaw 062eef6
Update CODEOWNERS
warsaw 8f744fb
Merge branch 'main' into pep-813-pprint
warsaw c8212a9
Merge branch 'main' into pep-813-pprint
warsaw 93b0d6e
Merge branch 'main' into pep-813-pprint
warsaw dfd5667
Update the PEP to match the latest decisions, and reference implement…
warsaw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,244 @@ | ||
| PEP: 813 | ||
| Title: The Pretty Print Protocol | ||
| Author: Barry Warsaw <[email protected]>, Eric V. Smith <[email protected]> | ||
| Discussions-To: Pending | ||
| Status: Draft | ||
| Type: Standards Track | ||
| Created: 07-Nov-2025 | ||
| Python-Version: 3.15 | ||
| Post-History: Pending | ||
|
|
||
|
|
||
| Abstract | ||
| ======== | ||
|
|
||
| This PEP describes the "pretty print protocol", a collection of changes proposed to make pretty printing more | ||
| customizable and convenient. | ||
|
|
||
|
|
||
| Motivation | ||
| ========== | ||
|
|
||
| "Pretty printing" is a feature which provides a capability to format object representations for better | ||
| readability. The core functionality is implemented by the standard library :mod:`pprint` module. ``pprint`` | ||
| includes a class and APIs which users can invoke to format and print more readable representations of objects, | ||
| versus the standard ``repr()`` built-in function. Important use cases include pretty printing large | ||
| dictionaries and other complicated objects for debugging purposes. | ||
|
|
||
| This PEP builds on the features of the module to provide more customization and user convenience. It is also | ||
| inspired by the `Rich library's pretty printing protocol | ||
| <https://rich.readthedocs.io/en/latest/pretty.html#rich-repr-protocol>`_. | ||
|
|
||
|
|
||
| Rationale | ||
| ========= | ||
|
|
||
| Pretty printing is very useful for displaying complex data structures, like dictionaries read from JSON | ||
| content. By providing a way for classes to customize how their instances participate in pretty printing, | ||
| users have more options for visually improving the display of their complex data, especially for debugging. | ||
|
|
||
| By extending the built-in :func:`print` function to automatically pretty print its output, debugging with | ||
| user-friendly display is made even more convenient. Since no extra imports are required, users can easily | ||
| just piggyback on well-worn "print debugging" patterns, at least for the most common use cases. | ||
|
|
||
| These extensions work both independently and complimentary, to provide powerful new use cases. | ||
|
|
||
|
|
||
| Specification | ||
| ============= | ||
|
|
||
| There are several parts to this proposal. | ||
|
|
||
|
|
||
| ``__pprint__()`` methods | ||
| ------------------------ | ||
|
|
||
| Classes can implement a new dunder method, ``__pprint__()`` which if present, generates parts of their | ||
| instance's pretty printed representation. This augments ``__repr__()`` which, prior to this proposal, was the | ||
| only method used to generate a custom representation of the object. Since object reprs provide functionality | ||
| distinct from pretty printing, some classes may want more control over their pretty display. The | ||
| :py:class:`python:pprint.PrettyPrinter` class is modified to respect an object's ``__pprint__()`` method if | ||
| present. | ||
|
|
||
| ``__pprint__()`` is optional; if missing, the standard pretty printers fall back to ``__repr__()`` for full | ||
| backward compatibility (technically speaking, :py:func:`python:pprint.saferepr` is used). However, if defined | ||
| on a class, ``__pprint__()`` takes a single argument, the object to be pretty printed (i.e. ``self``). | ||
|
|
||
| The method is expected to return or yield a sequence of values, which are used to construct a pretty | ||
| representation of the object. These values are wrapped in standard class "chrome", such as the | ||
| class name. The printed representation will usually look like a class constructor, with positional, | ||
| keyword, and default arguments. The values can be any of the following formats: | ||
|
|
||
| * A single value, representing a positional argument. The value itself is used. | ||
| * A 2-tuple of ``(name, value)`` representing a keyword argument. A representation of | ||
| ``name=value`` is used. | ||
| * A 3-tuple of ``(name, value, default_value)`` representing a keyword argument with a default | ||
| value. If ``value`` equals ``default_value``, then this tuple is skipped, otherwise | ||
| ``name=value`` is used. | ||
|
|
||
| .. note:: | ||
|
|
||
| This protocol is compatible with the `Rich library's pretty printing protocol | ||
| <https://rich.readthedocs.io/en/latest/pretty.html#rich-repr-protocol>`_. | ||
|
|
||
|
|
||
| A new argument to built-in ``print`` | ||
| ------------------------------------ | ||
|
|
||
| Built-in :func:`print` takes a new optional argument, appended to the end of the argument list, called | ||
| ``pretty``, which can take one of the following values: | ||
|
|
||
| * ``None`` - the default. No pretty printing is invoked. Fully backward compatible. | ||
| * ``True`` - use a temporary instance of the :py:class:`python:pprint.PrettyPrinter` class to get a | ||
| pretty representation of the object. | ||
| * An instance with a ``pformat()`` method, which has the same signature as | ||
| :py:meth:`python:pprint.PrettyPrinter.pformat`. When given, this will usually be an instance of a | ||
| subclass of ``PrettyPrinter`` with its ``pformat()`` method overridden. Note that this form | ||
| requires **an instance** of a pretty printer, not a class, as only ``print(..., pretty=True)`` | ||
| performs implicit instantiation. | ||
|
|
||
|
|
||
| Examples | ||
| ======== | ||
|
|
||
| A custom ``__pprint__()`` method can be used to customize the representation of the object, such as with this | ||
| class: | ||
|
|
||
| .. code-block:: python | ||
|
|
||
| class Bass: | ||
| def __init__(self, strings: int, pickups: str, active: bool=False): | ||
| self._strings = strings | ||
| self._pickups = pickups | ||
| self._active = active | ||
|
|
||
| def __pprint__(self): | ||
| yield self._strings | ||
| yield 'pickups', self._pickups | ||
| yield 'active', self._active, False | ||
|
|
||
| Now let's create a couple of instances, and pretty print them: | ||
|
|
||
| .. code-block:: pycon | ||
|
|
||
| >>> precision = Bass(4, 'split coil P', active=False) | ||
| >>> stingray = Bass(5, 'humbucker', active=True) | ||
|
|
||
| >>> pprint.pprint(precision) | ||
| Bass(4, pickups='split coil P') | ||
| >>> pprint.pprint(stingray) | ||
| Bass(5, pickups='humbucker', active=True) | ||
|
|
||
| Here's an example of using the ``pretty`` argument to built-in ``print()``: | ||
|
|
||
| .. code-block:: pycon | ||
|
|
||
| >>> import os | ||
| >>> print(os.pathconf_names) | ||
| {'PC_ASYNC_IO': 17, 'PC_CHOWN_RESTRICTED': 7, 'PC_FILESIZEBITS': 18, 'PC_LINK_MAX': 1, 'PC_MAX_CANON': 2, 'PC_MAX_INPUT': 3, 'PC_NAME_MAX': 4, 'PC_NO_TRUNC': 8, 'PC_PATH_MAX': 5, 'PC_PIPE_BUF': 6, 'PC_PRIO_IO': 19, 'PC_SYNC_IO': 25, 'PC_VDISABLE': 9, 'PC_MIN_HOLE_SIZE': 27, 'PC_ALLOC_SIZE_MIN': 16, 'PC_REC_INCR_XFER_SIZE': 20, 'PC_REC_MAX_XFER_SIZE': 21, 'PC_REC_MIN_XFER_SIZE': 22, 'PC_REC_XFER_ALIGN': 23, 'PC_SYMLINK_MAX': 24} | ||
|
|
||
| >>> print(os.pathconf_names, pretty=True) | ||
| {'PC_ALLOC_SIZE_MIN': 16, | ||
| 'PC_ASYNC_IO': 17, | ||
| 'PC_CHOWN_RESTRICTED': 7, | ||
| 'PC_FILESIZEBITS': 18, | ||
| 'PC_LINK_MAX': 1, | ||
| 'PC_MAX_CANON': 2, | ||
| 'PC_MAX_INPUT': 3, | ||
| 'PC_MIN_HOLE_SIZE': 27, | ||
| 'PC_NAME_MAX': 4, | ||
| 'PC_NO_TRUNC': 8, | ||
| 'PC_PATH_MAX': 5, | ||
| 'PC_PIPE_BUF': 6, | ||
| 'PC_PRIO_IO': 19, | ||
| 'PC_REC_INCR_XFER_SIZE': 20, | ||
| 'PC_REC_MAX_XFER_SIZE': 21, | ||
| 'PC_REC_MIN_XFER_SIZE': 22, | ||
| 'PC_REC_XFER_ALIGN': 23, | ||
| 'PC_SYMLINK_MAX': 24, | ||
| 'PC_SYNC_IO': 25, | ||
| 'PC_VDISABLE': 9} | ||
|
|
||
|
|
||
| Backwards Compatibility | ||
| ======================= | ||
|
|
||
| When none of the new features are used, this PEP is fully backward compatible, both for built-in | ||
| ``print()`` and the ``pprint`` module. | ||
|
|
||
|
|
||
| Security Implications | ||
| ===================== | ||
|
|
||
| There are no known security implications for this proposal. | ||
|
|
||
|
|
||
| How to Teach This | ||
| ================= | ||
|
|
||
| Documentation and examples are added to the ``pprint`` module and the ``print()`` function. | ||
| Beginners don't need to be taught these new features until they want prettier representations of | ||
| their objects. | ||
|
|
||
|
|
||
| Reference Implementation | ||
| ======================== | ||
|
|
||
| The reference implementation is currently available as a `PEP author branch of the CPython main | ||
| branch <https://github.com/warsaw/cpython/tree/pprint>`__. | ||
|
|
||
|
|
||
| Rejected Ideas | ||
| ============== | ||
|
|
||
| None at this time. | ||
|
|
||
|
|
||
| Open Issues | ||
| =========== | ||
|
|
||
| The output format and APIs are heavily inspired by `Rich | ||
| <https://rich.readthedocs.io/en/latest/pretty.html#rich-repr-protocol>`_. The idea is that Rich could | ||
| implement an API compatible with ``print(..., pretty=RichPrinter)`` fairly easily. Rich's API is designed to | ||
| print constructor-like representations of instances, which means that it's not possible to control much of the | ||
| "class chrome" around the arguments. Rich does support using angle brackets (i.e. ``<...>``) instead of | ||
| parentheses by setting the attribute ``.angular=True`` on the rich repr method. This PEP does not support | ||
| that feature, although it likely could in the future. | ||
|
|
||
| This also means that there's no way to control the pretty printed format of built-in types like strings, | ||
| dicts, lists, etc. This seems fine as ``pprint`` is not intended to be as feature-rich (pun intended!) as | ||
| Rich. This PEP purposefully deems such fancy features as out-of-scope. | ||
|
|
||
| One consequence of ``print(..., pretty=True)`` is that it can be more less obvious if you wanted to print | ||
| multiple objects with, say a newline between the object representations. Compare these two outputs: | ||
|
|
||
| .. code-block:: pycon | ||
|
|
||
| >>> print(precision, '\n', stingray, pretty=True) | ||
| Bass(4, pickups='split coil P') '\n' Bass(5, pickups='humbucker', active=True) | ||
|
|
||
| >>> print(precision, stingray, sep='\n', pretty=True) | ||
| Bass(4, pickups='split coil P') | ||
| Bass(5, pickups='humbucker', active=True) | ||
|
|
||
| It's likely you'll want the second output, but more complicated multi-object displays could get even less | ||
| convenient and/or more verbose. | ||
|
|
||
|
|
||
| Acknowledgments | ||
| =============== | ||
|
|
||
| TBD | ||
|
|
||
|
|
||
| Footnotes | ||
| ========= | ||
|
|
||
| TBD | ||
|
|
||
|
|
||
| Copyright | ||
| ========= | ||
|
|
||
| This document is placed in the public domain or under the | ||
| CC0-1.0-Universal license, whichever is more permissive. | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.