• Stars
    star
    408
  • Rank 105,946 (Top 3 %)
  • Language
    Python
  • License
    Other
  • Created over 10 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

pprint++: a drop-in replacement for pprint that's actually pretty

pprint++: a drop-in replacement for pprint that's actually pretty

https://travis-ci.org/wolever/pprintpp.svg?branch=master

Now with Python 3 support!

Installation

pprint++ can be installed with Python 2 or Python 3 using pip or easy_install:

$ pip install pprintpp
- OR -
$ easy_install pprintpp

Usage

pprint++ can be used in three ways:

  1. Through the separate pp package:

    $ pip install pp-ez
    $ python
    ...
    >>> import pp
    >>> pp(["Hello", "world"])
    ["Hello", "world"]
    

    For more, see https://pypi.python.org/pypi/pp-ez

  2. As a command-line program, which will read Python literals from standard in and pretty-print them:

    $ echo "{'hello': 'world'}" | pypprint
    {'hello': 'world'}
    
  3. As an ipython extension:

    In [1]: %load_ext pprintpp
    

    This will use pprintpp for ipython's output.

    To load this extension when ipython starts, put the previous line in your startup file.

    You can change the indentation level like so:

    In [2]: %config PPrintPP.indentation = 4
    
  4. To monkeypatch pprint:

    >>> import pprintpp
    >>> pprintpp.monkeypatch()
    >>> import pprint
    >>> pprint.pprint(...)
    

    Note: the original pprint module will be available with import pprint_original. Additionally, a warning will be issued if pprint has already been imported. This can be suppressed by passing quiet=True.

  5. And, if you really want, it can even be imported as a regular module:

    >>> import pprintpp
    >>> pprintpp.pprint(...)

Usability Protips

pp

For bonus code aesthetics, pprintpp.pprint can be imported as pp:

>>> from pprintpp import pprint as pp
>>> pp(...)

And if that is just too many letters, the pp-ez package can be installed from PyPI, ensuring that pretty-printing is never more than an import pp away:

$ pip install pp-ez
$ python
...
>>> import pp
>>> pp(["Hello", "world"])
["Hello", "world"]

For more, see https://pypi.python.org/pypi/pp-ez

Why is it prettier?

Unlike pprint, pprint++ strives to emit a readable, largely PEP8-compliant, representation of its input.

It also has explicit support for: the collections module (defaultdict and Counter) and numpy arrays:

>>> import numpy as np
>>> from collections import defaultdict, Counter
>>> pprint([np.array([[1,2],[3,4]]), defaultdict(int, {"foo": 1}), Counter("aaabbc")])
[
    array([[1, 2],
           [3, 4]]),
    defaultdict(<type 'int'>, {'foo': 1}),
    Counter({'a': 3, 'b': 2, 'c': 1}),
]

Unicode characters, when possible, will be printed un-escaped. This is done by checking both the output stream's encoding (defaulting to utf-8) and the character's Unicode category. An effort is made to print only characters which will be visually unambiguous: letters and numbers will be printed un-escaped, spaces, combining characters, and control characters will be escaped:

>>> unistr = u"\xe9e\u0301"
>>> print unistr
éé
>>> pprint(unistr)
u'ée\u0301'

The output stream's encoding will be considered too:

>>> import io
>>> stream = io.BytesIO()
>>> stream.encoding = "ascii"
>>> pprint(unistr, stream=stream)
>>> print stream.getvalue()
u'\xe9e\u0301'

Subclassess of built-in collection types which don't define a new __repr__ will have their class name explicitly added to their repr. For example:

>>> class MyList(list):
...     pass
...
>>> pprint(MyList())
MyList()
>>> pprint(MyList([1, 2, 3]))
MyList([1, 2, 3])

Note that, as you might expect, custom __repr__ methods will be respected:

>>> class MyList(list):
...     def __repr__(self):
...         return "custom repr!"
...
>>> pprint(MyList())
custom repr!

Note: pprint++ is still under development, so the format will change and improve over time.

Example

With printpp:

>>> import pprintpp
>>> pprintpp.pprint(["Hello", np.array([[1,2],[3,4]])])
[
    'Hello',
    array([[1, 2],
           [3, 4]]),
]
>>> pprintpp.pprint(tweet)
{
    'coordinates': None,
    'created_at': 'Mon Jun 27 19:32:19 +0000 2011',
    'entities': {
        'hashtags': [],
        'urls': [
            {
                'display_url': 'tumblr.com/xnr37hf0yz',
                'expanded_url': 'http://tumblr.com/xnr37hf0yz',
                'indices': [107, 126],
                'url': 'http://t.co/cCIWIwg',
            },
        ],
        'user_mentions': [],
    },
    'place': None,
    'source': '<a href="http://www.tumblr.com/" rel="nofollow">Tumblr</a>',
    'truncated': False,
    'user': {
        'contributors_enabled': True,
        'default_profile': False,
        'entities': {'hashtags': [], 'urls': [], 'user_mentions': []},
        'favourites_count': 20,
        'id_str': '6253282',
        'profile_link_color': '0094C2',
    },
}

Without printpp:

>>> import pprint
>>> import numpy as np
>>> pprint.pprint(["Hello", np.array([[1,2],[3,4]])])
['Hello', array([[1, 2],
       [3, 4]])]
>>> tweet = {'coordinates': None, 'created_at': 'Mon Jun 27 19:32:19 +0000 2011', 'entities': {'hashtags': [], 'urls': [{'display_url': 'tumblr.com/xnr37hf0yz', 'expanded_url': 'http://tumblr.com/xnr37hf0yz', 'indices': [107, 126], 'url': 'http://t.co/cCIWIwg'}], 'user_mentions': []}, 'place': None, 'source': '<a href="http://www.tumblr.com/" rel="nofollow">Tumblr</a>', 'truncated': False, 'user': {'contributors_enabled': True, 'default_profile': False, 'entities': {'hashtags': [], 'urls': [], 'user_mentions': []}, 'favourites_count': 20, 'id_str': '6253282', 'profile_link_color': '0094C2'}}
>>> pprint.pprint(tweet)
{'coordinates': None,
 'created_at': 'Mon Jun 27 19:32:19 +0000 2011',
 'entities': {'hashtags': [],
              'urls': [{'display_url': 'tumblr.com/xnr37hf0yz',
                        'expanded_url': 'http://tumblr.com/xnr37hf0yz',
                        'indices': [107, 126],
                        'url': 'http://t.co/cCIWIwg'}],
              'user_mentions': []},
 'place': None,
 'source': '<a href="http://www.tumblr.com/" rel="nofollow">Tumblr</a>',
 'truncated': False,
 'user': {'contributors_enabled': True,
          'default_profile': False,
          'entities': {'hashtags': [], 'urls': [], 'user_mentions': []},
          'favourites_count': 20,
          'id_str': '6253282',
          'profile_link_color': '0094C2'}}

More Repositories

1

parameterized

Parameterized testing with any Python test framework
Python
829
star
2

pip2pi

pip2pi builds a PyPI-compatible package repository from pip requirements
Python
750
star
3

python-cffi-example

A simple example Python + CFFI package (including testing, development, and packaging)
Python
115
star
4

autorepr

Easily implement __repr__, __str__, and __unicode__ methods
Python
49
star
5

git-blast

git-blast: show git branches sorted by last commit date
Python
38
star
6

browsercast

An IPython notebook plugin which facilitates lecture recording and playback.
JavaScript
34
star
7

pg-histogram

PostgreSQL functions for generating text-based histograms
PLpgSQL
31
star
8

wayslack

The Wayslack Machine: incrementally archive Slack messages and files using Slack's team export format
Python
23
star
9

Protocol-Informatics

Patches to the Protocol Informatics project to make it work with a numpy.
C
20
star
10

django-switchuser

django-switchuser makes it easy for an administrator to switch to temporarily switch to another account by visiting /su.
Python
16
star
11

libzbar-cffi

Python cffi-based bindings for the zbar QR decoder (Py2, Py3, and PyPy)
C
13
star
12

remora

remora: less insane JavaScript templating
JavaScript
13
star
13

dwdj

A collection of useful Django utilities.
Python
9
star
14

libqrencode-cffi

Fast, robust, and less incomplete Python cffi-based bindings for libqrencode
C
7
star
15

vcslog

Logs interactions with version control systems
Python
7
star
16

monte-carlo-monopoly

A Monte Carlo Monopoly simulation
C
6
star
17

openssl-x509-scripts

Scripts for creating an x509 certificate authority and using it to create and sign certificates.
4
star
18

nfa2regex

Converts NFAs (and DFAs) to a regular expressions using the state removal method.
Go
4
star
19

gevent-helpers

A collection of utilities which are helpful while developing with gevent
Python
4
star
20

jquery-wakeful

A REST-aware RPC protocol and jQuery based client
Python
3
star
21

dupecert

Duplicates SSL certificates
Python
3
star
22

safesort

Safely sort heterogeneous collections on Python 2 and 3
Python
3
star
23

pycon-slides

App which handles uploading of PyCon speaker slides
Python
3
star
24

git-ibisect

git-ibisect: interactively run git-bisect
Python
3
star
25

facebook-archive-parser

A fast Python-based parser for Facebook's archive format
Jupyter Notebook
3
star
26

python-smart-imports.vim

(WORK IN PROGRESS) python-smart-imports.vim - intelligently adds imports to Python files
Python
2
star
27

logging-assertions

Easily make assertions about logged messages in tests
Python
2
star
28

randchk

Randomly checksum files to ensure the integrity of backups.
Python
2
star
29

react-use-async-result

Simple, Sound, Type-Safe Promises in React Components
TypeScript
2
star
30

backup-chk

(WORK IN PROGRESS) incrementally verify backup integrity, with specific support for Time Machine
Go
1
star
31

clog-ansible

Ansible playbook for clog configuration
1
star
32

onioncrypt

onioncrypt: encrypt a file with multiple levels of encryption to multiple people.
Python
1
star
33

djto-testing-micropatterns-talk

Notes from my Django Toronto Testing Micropatterns talk
1
star
34

python-safe_cmp

safe_cmp: safe comparisons (total ordering) for any object in Python 3
Python
1
star
35

homebrew-git-blast

Homebrew Tap for git-blast
Ruby
1
star
36

postgres-functions

A collection of useful PostgreSQL functions
PLpgSQL
1
star
37

pg-change-logs

Automatically manages audit logs for Postgres databases
PLpgSQL
1
star
38

python-test-helper

A modular, composable interface for libraries to expose testing tools
1
star
39

songdb

An improved song database for #LoserKaraoke
JavaScript
1
star
40

wsgi-cloudflare-proxy-fix

Sets REMOTE_ADDR to the correct value when behind Cloudflare, based on the X-Real-IP header, when requests originate from Cloudflare's IP range.
Python
1
star