cpython: 5a2296093645 (original) (raw)
--- a/Doc/library/pprint.rst
+++ b/Doc/library/pprint.rst
@@ -14,8 +14,8 @@ The :mod:pprint
module provides a capa
Python data structures in a form which can be used as input to the interpreter.
If the formatted structures include objects which are not fundamental Python
types, the representation may not be loadable. This may be the case if objects
-such as files, sockets, classes, or instances are included, as well as many
-other built-in objects which are not representable as Python constants.
+such as files, sockets or classes are included, as well as many other
+objects which are not representable as Python literals.
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.
@@ -65,7 +65,7 @@ The :mod:pprint
module defines one cla
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
-The :class:PrettyPrinter
class supports several derivative functions:
+The :mod:pprint
module also provides several shortcut functions:
.. function:: pformat(object, indent=1, width=80, depth=None)
@@ -193,101 +193,141 @@ Example
-------
To demonstrate several uses of the :func:pprint
function and its parameters,
-let's fetch information about a project from PyPI::
+let's fetch information about a project from PyPI <https://pypi.python.org>
_::
>>> import json
>>> import pprint
>>> from urllib.request import urlopen
with urlopen('http://pypi.python.org/pypi/configparser/json') as url:
with urlopen('http://pypi.python.org/pypi/Twisted/json') as url: ... http_info = url.info() ... raw_data = url.read().decode(http_info.get_content_charset()) project_info = json.loads(raw_data)
In its basic form, :func:pprint
shows the whole object::
- {'body': {'info': {'_pypi_hidden': False,
'_pypi_ordering': 12,[](#l1.44)
'classifiers': ['Development Status :: 4 - Beta',[](#l1.45)
'Intended Audience :: Developers',[](#l1.46)
'License :: OSI Approved :: MIT License',[](#l1.47)
'Natural Language :: English',[](#l1.48)
'Operating System :: OS Independent',[](#l1.49)
'Programming Language :: Python',[](#l1.50)
'Programming Language :: Python :: 2',[](#l1.51)
'Programming Language :: Python :: 2.6',[](#l1.52)
'Programming Language :: Python :: 2.7',[](#l1.53)
'Topic :: Software Development :: Libraries',[](#l1.54)
'Topic :: Software Development :: Libraries :: Python Modules'],[](#l1.55)
'download_url': 'UNKNOWN',[](#l1.56)
'home_page': 'http://docs.python.org/py3k/library/configparser.html',[](#l1.57)
'keywords': 'configparser ini parsing conf cfg configuration file',[](#l1.58)
'license': 'MIT',[](#l1.59)
'name': 'configparser',[](#l1.60)
'package_url': 'http://pypi.python.org/pypi/configparser',[](#l1.61)
'platform': 'any',[](#l1.62)
'release_url': 'http://pypi.python.org/pypi/configparser/3.2.0r3',[](#l1.63)
'requires_python': None,[](#l1.64)
'stable_version': None,[](#l1.65)
'summary': 'This library brings the updated configparser from Python 3.2+ to Python 2.6-2.7.',[](#l1.66)
'version': '3.2.0r3'},[](#l1.67)
'urls': [{'comment_text': '',[](#l1.68)
'downloads': 47,[](#l1.69)
'filename': 'configparser-3.2.0r3.tar.gz',[](#l1.70)
'has_sig': False,[](#l1.71)
'md5_digest': '8500fd87c61ac0de328fc996fce69b96',[](#l1.72)
'packagetype': 'sdist',[](#l1.73)
'python_version': 'source',[](#l1.74)
'size': 32281,[](#l1.75)
'upload_time': '2011-05-10T16:28:50',[](#l1.76)
'url': 'http://pypi.python.org/packages/source/c/configparser/configparser-3.2.0r3.tar.gz'}]},[](#l1.77)
- 'headers': [('Date', 'Sat, 14 May 2011 12:48:52 GMT'),
('Server', 'Apache/2.2.16 (Debian)'),[](#l1.79)
('Content-Disposition', 'inline'),[](#l1.80)
('Connection', 'close'),[](#l1.81)
('Transfer-Encoding', 'chunked'),[](#l1.82)
('Content-Type', 'application/json; charset="UTF-8"')]}[](#l1.83)
- {'info': {'_pypi_hidden': False,
'_pypi_ordering': 125,[](#l1.86)
'author': 'Glyph Lefkowitz',[](#l1.87)
'author_email': 'glyph@twistedmatrix.com',[](#l1.88)
'bugtrack_url': '',[](#l1.89)
'cheesecake_code_kwalitee_id': None,[](#l1.90)
'cheesecake_documentation_id': None,[](#l1.91)
'cheesecake_installability_id': None,[](#l1.92)
'classifiers': ['Programming Language :: Python :: 2.6',[](#l1.93)
'Programming Language :: Python :: 2.7',[](#l1.94)
'Programming Language :: Python :: 2 :: Only'],[](#l1.95)
'description': 'An extensible framework for Python programming, '[](#l1.96)
'with special focus\r\n'[](#l1.97)
'on event-based network programming and '[](#l1.98)
'multiprotocol integration.',[](#l1.99)
'docs_url': '',[](#l1.100)
'download_url': 'UNKNOWN',[](#l1.101)
'home_page': 'http://twistedmatrix.com/',[](#l1.102)
'keywords': '',[](#l1.103)
'license': 'MIT',[](#l1.104)
'maintainer': '',[](#l1.105)
'maintainer_email': '',[](#l1.106)
'name': 'Twisted',[](#l1.107)
'package_url': 'http://pypi.python.org/pypi/Twisted',[](#l1.108)
'platform': 'UNKNOWN',[](#l1.109)
'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',[](#l1.110)
'requires_python': None,[](#l1.111)
'stable_version': None,[](#l1.112)
'summary': 'An asynchronous networking framework written in Python',[](#l1.113)
'version': '12.3.0'},[](#l1.114)
- 'urls': [{'comment_text': '',
'downloads': 71844,[](#l1.116)
'filename': 'Twisted-12.3.0.tar.bz2',[](#l1.117)
'has_sig': False,[](#l1.118)
'md5_digest': '6e289825f3bf5591cfd670874cc0862d',[](#l1.119)
'packagetype': 'sdist',[](#l1.120)
'python_version': 'source',[](#l1.121)
'size': 2615733,[](#l1.122)
'upload_time': '2012-12-26T12:47:03',[](#l1.123)
'url': 'https://pypi.python.org/packages/source/T/Twisted/Twisted-12.3.0.tar.bz2'},[](#l1.124)
{'comment_text': '',[](#l1.125)
'downloads': 5224,[](#l1.126)
'filename': 'Twisted-12.3.0.win32-py2.7.msi',[](#l1.127)
'has_sig': False,[](#l1.128)
'md5_digest': '6b778f5201b622a5519a2aca1a2fe512',[](#l1.129)
'packagetype': 'bdist_msi',[](#l1.130)
'python_version': '2.7',[](#l1.131)
'size': 2916352,[](#l1.132)
'upload_time': '2012-12-26T12:48:15',[](#l1.133)
'url': 'https://pypi.python.org/packages/2.7/T/Twisted/Twisted-12.3.0.win32-py2.7.msi'}]}[](#l1.134)
The result can be limited to a certain depth (ellipsis is used for deeper contents)::
- {'body': {'info': {'_pypi_hidden': False,
'_pypi_ordering': 12,[](#l1.141)
'classifiers': [...],[](#l1.142)
'download_url': 'UNKNOWN',[](#l1.143)
'home_page': 'http://docs.python.org/py3k/library/configparser.html',[](#l1.144)
'keywords': 'configparser ini parsing conf cfg configuration file',[](#l1.145)
'license': 'MIT',[](#l1.146)
'name': 'configparser',[](#l1.147)
'package_url': 'http://pypi.python.org/pypi/configparser',[](#l1.148)
'platform': 'any',[](#l1.149)
'release_url': 'http://pypi.python.org/pypi/configparser/3.2.0r3',[](#l1.150)
'requires_python': None,[](#l1.151)
'stable_version': None,[](#l1.152)
'summary': 'This library brings the updated configparser from Python 3.2+ to Python 2.6-2.7.',[](#l1.153)
'version': '3.2.0r3'},[](#l1.154)
'urls': [{...}]},[](#l1.155)
- 'headers': [('Date', 'Sat, 14 May 2011 12:48:52 GMT'),
('Server', 'Apache/2.2.16 (Debian)'),[](#l1.157)
('Content-Disposition', 'inline'),[](#l1.158)
('Connection', 'close'),[](#l1.159)
('Transfer-Encoding', 'chunked'),[](#l1.160)
('Content-Type', 'application/json; charset="UTF-8"')]}[](#l1.161)
- {'info': {'_pypi_hidden': False,
'_pypi_ordering': 125,[](#l1.164)
'author': 'Glyph Lefkowitz',[](#l1.165)
'author_email': 'glyph@twistedmatrix.com',[](#l1.166)
'bugtrack_url': '',[](#l1.167)
'cheesecake_code_kwalitee_id': None,[](#l1.168)
'cheesecake_documentation_id': None,[](#l1.169)
'cheesecake_installability_id': None,[](#l1.170)
'classifiers': [...],[](#l1.171)
'description': 'An extensible framework for Python programming, '[](#l1.172)
'with special focus\r\n'[](#l1.173)
'on event-based network programming and '[](#l1.174)
'multiprotocol integration.',[](#l1.175)
'docs_url': '',[](#l1.176)
'download_url': 'UNKNOWN',[](#l1.177)
'home_page': 'http://twistedmatrix.com/',[](#l1.178)
'keywords': '',[](#l1.179)
'license': 'MIT',[](#l1.180)
'maintainer': '',[](#l1.181)
'maintainer_email': '',[](#l1.182)
'name': 'Twisted',[](#l1.183)
'package_url': 'http://pypi.python.org/pypi/Twisted',[](#l1.184)
'platform': 'UNKNOWN',[](#l1.185)
'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',[](#l1.186)
'requires_python': None,[](#l1.187)
'stable_version': None,[](#l1.188)
'summary': 'An asynchronous networking framework written in Python',[](#l1.189)
'version': '12.3.0'},[](#l1.190)
- 'urls': [{...}, {...}]}
+ +Additionally, maximum character width can be suggested. If a long object +cannot be split, the specified width will be exceeded:: -Additionally, maximum width can be suggested. If a long object cannot be -split, the specified width will be exceeded:: -
- [('Date',
'Sat, 14 May 2011 12:48:52 GMT'),[](#l1.201)
- ('Server',
'Apache/2.2.16 (Debian)'),[](#l1.203)
- ('Content-Disposition',
'inline'),[](#l1.205)
- ('Connection', 'close'),
- ('Transfer-Encoding',
'chunked'),[](#l1.208)
- ('Content-Type',
'application/json; charset="UTF-8"')][](#l1.210)
- {'info': {'_pypi_hidden': False,
'_pypi_ordering': 125,[](#l1.213)
'author': 'Glyph Lefkowitz',[](#l1.214)
'author_email': 'glyph@twistedmatrix.com',[](#l1.215)
'bugtrack_url': '',[](#l1.216)
'cheesecake_code_kwalitee_id': None,[](#l1.217)
'cheesecake_documentation_id': None,[](#l1.218)
'cheesecake_installability_id': None,[](#l1.219)
'classifiers': [...],[](#l1.220)
'description': 'An extensible '[](#l1.221)
'framework for '[](#l1.222)
'Python programming, '[](#l1.223)
'with special '[](#l1.224)
'focus\r\n'[](#l1.225)
'on event-based '[](#l1.226)
'network programming '[](#l1.227)
'and multiprotocol '[](#l1.228)
'integration.',[](#l1.229)
'docs_url': '',[](#l1.230)
'download_url': 'UNKNOWN',[](#l1.231)
'home_page': 'http://twistedmatrix.com/',[](#l1.232)
'keywords': '',[](#l1.233)
'license': 'MIT',[](#l1.234)
'maintainer': '',[](#l1.235)
'maintainer_email': '',[](#l1.236)
'name': 'Twisted',[](#l1.237)
'package_url': 'http://pypi.python.org/pypi/Twisted',[](#l1.238)
'platform': 'UNKNOWN',[](#l1.239)
'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',[](#l1.240)
'requires_python': None,[](#l1.241)
'stable_version': None,[](#l1.242)
'summary': 'An asynchronous '[](#l1.243)
'networking framework '[](#l1.244)
'written in Python',[](#l1.245)
'version': '12.3.0'},[](#l1.246)
- 'urls': [{...}, {...}]}
--- a/Lib/pprint.py +++ b/Lib/pprint.py @@ -34,6 +34,7 @@ saferepr() """ +import re import sys as _sys from collections import OrderedDict as _OrderedDict from io import StringIO as _StringIO @@ -158,13 +159,10 @@ class PrettyPrinter: return rep = self._repr(object, context, level - 1) typ = _type(object)
sepLines = _len(rep) > (self._width - 1 - indent - allowance)[](#l2.15)
max_width = self._width - 1 - indent - allowance[](#l2.16)
sepLines = _len(rep) > max_width[](#l2.17) write = stream.write[](#l2.18)
if self._depth and level > self._depth:[](#l2.20)
write(rep)[](#l2.21)
return[](#l2.22)
- if sepLines: r = getattr(typ, "repr", None) if issubclass(typ, dict): @@ -242,6 +240,37 @@ class PrettyPrinter: write(endchar) return
if issubclass(typ, str) and len(object) > 0 and r is str.__repr__:[](#l2.31)
def _str_parts(s):[](#l2.32)
"""[](#l2.33)
Return a list of string literals comprising the repr()[](#l2.34)
of the given string using literal concatenation.[](#l2.35)
"""[](#l2.36)
lines = s.splitlines(True)[](#l2.37)
for i, line in enumerate(lines):[](#l2.38)
rep = repr(line)[](#l2.39)
if _len(rep) <= max_width:[](#l2.40)
yield rep[](#l2.41)
else:[](#l2.42)
# A list of alternating (non-space, space) strings[](#l2.43)
parts = re.split(r'(\s+)', line) + [''][](#l2.44)
current = ''[](#l2.45)
for i in range(0, len(parts), 2):[](#l2.46)
part = parts[i] + parts[i+1][](#l2.47)
candidate = current + part[](#l2.48)
if len(repr(candidate)) > max_width:[](#l2.49)
if current:[](#l2.50)
yield repr(current)[](#l2.51)
current = part[](#l2.52)
else:[](#l2.53)
current = candidate[](#l2.54)
if current:[](#l2.55)
yield repr(current)[](#l2.56)
for i, rep in enumerate(_str_parts(object)):[](#l2.57)
if i > 0:[](#l2.58)
write('\n' + ' '*indent)[](#l2.59)
write(rep)[](#l2.60)
return[](#l2.61) write(rep)[](#l2.62)
def _repr(self, object, context, level):
--- a/Lib/test/test_pprint.py +++ b/Lib/test/test_pprint.py @@ -1,3 +1,5 @@ +# -- coding: utf-8 -- + import pprint import test.support import unittest @@ -475,6 +477,42 @@ class QueryTestCase(unittest.TestCase): self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)), '{%r: 0, %r: 0}' % tuple(sorted(keys, key=id)))
- def test_str_wrap(self):
# pprint tries to wrap strings intelligently[](#l3.14)
fox = 'the quick brown fox jumped over a lazy dog'[](#l3.15)
self.assertEqual(pprint.pformat(fox, width=20), """\[](#l3.16)
+'the quick brown ' +'fox jumped over ' +'a lazy dog'""")
self.assertEqual(pprint.pformat({'a': 1, 'b': fox, 'c': 2},[](#l3.20)
width=26), """\[](#l3.21)
- 'b': 'the quick brown '
'fox jumped over '[](#l3.24)
'a lazy dog',[](#l3.25)
- 'c': 2}""")
# With some special characters[](#l3.27)
# - \n always triggers a new line in the pprint[](#l3.28)
# - \t and \n are escaped[](#l3.29)
# - non-ASCII is allowed[](#l3.30)
# - an apostrophe doesn't disrupt the pprint[](#l3.31)
special = "Portons dix bons \"whiskys\"\nà l'avocat goujat\t qui fumait au zoo"[](#l3.32)
self.assertEqual(pprint.pformat(special, width=20), """\[](#l3.33)
+'Portons dix bons ' +'"whiskys"\n' +"à l'avocat " +'goujat\t qui ' +'fumait au zoo'""")
# An unwrappable string is formatted as its repr[](#l3.39)
unwrappable = "x" * 100[](#l3.40)
self.assertEqual(pprint.pformat(unwrappable, width=80), repr(unwrappable))[](#l3.41)
self.assertEqual(pprint.pformat(''), "''")[](#l3.42)
# Check that the pprint is a usable repr[](#l3.43)
special *= 10[](#l3.44)
for width in range(3, 40):[](#l3.45)
formatted = pprint.pformat(special, width=width)[](#l3.46)
self.assertEqual(eval("(" + formatted + ")"), special)[](#l3.47)
+ class DottedPrettyPrinter(pprint.PrettyPrinter):
--- a/Misc/NEWS +++ b/Misc/NEWS @@ -294,6 +294,9 @@ Core and Builtins Library ------- +- Issue #17150: pprint now uses line continuations to wrap long string