Giter Site home page Giter Site logo

pprintpp's Introduction

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'}}

pprintpp's People

Contributors

ahawker avatar hugovk avatar jbaum98 avatar marc1n avatar r0h1t4sh avatar roee30 avatar shazow avatar wolever avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pprintpp's Issues

ipython: installed but says cant find it

:/usr/local/lib/python2.7/dist-packages#  pip install pprintpp
Collecting pprintpp
  Downloading https://files.pythonhosted.org/packages/4e/d1/e4ed95fdd3ef13b78630280d9e9e240aeb65cc7c544ec57106149c3942fb/pprintpp-0.4.0-py2.py3-none-any.whl
Installing collected packages: pprintpp
Successfully installed pprintpp-0.4.0

In [2]: %load_ext printpp
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-2-a7f773a96ad6> in <module>()
----> 1 get_ipython().magic(u'load_ext printpp')

/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
   2158         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2159         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2160         return self.run_line_magic(magic_name, magic_arg_s)
   2161 
   2162     #-------------------------------------------------------------------------

/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
   2079                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2080             with self.builtin_trap:
-> 2081                 result = fn(*args,**kwargs)
   2082             return result
   2083 

</usr/local/lib/python2.7/dist-packages/decorator.pyc:decorator-gen-63> in load_ext(self, module_str)

/usr/lib/python2.7/dist-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
    186     # but it's overkill for just that one bit of state.
    187     def magic_deco(arg):
--> 188         call = lambda f, *a, **k: f(*a, **k)
    189 
    190         if callable(arg):

/usr/lib/python2.7/dist-packages/IPython/core/magics/extension.pyc in load_ext(self, module_str)
     35         if not module_str:
     36             raise UsageError('Missing module name.')
---> 37         res = self.shell.extension_manager.load_extension(module_str)
     38 
     39         if res == 'already loaded':

/usr/lib/python2.7/dist-packages/IPython/core/extensions.pyc in load_extension(self, module_str)
     81             if module_str not in sys.modules:
     82                 with prepended_to_syspath(self.ipython_extension_dir):
---> 83                     __import__(module_str)
     84             mod = sys.modules[module_str]
     85             if self._call_load_ipython_extension(mod):

ImportError: No module named printpp


Frozenset bug.

pprintpp.pprint({6,frozenset({78, 32, 342}),8})

fails with

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jonathan/.virtualenvs/.../local/lib/python2.7/site-packages/pprintpp.py", line 94, in pprint
    printer.pprint(object)
  File "/home/jonathan/.virtualenvs/.../local/lib/python2.7/site-packages/pprintpp.py", line 236, in pprint
    self._format(object, state)
  File "/home/jonathan/.virtualenvs/.../local/lib/python2.7/site-packages/pprintpp.py", line 349, in _format
    self._format_nested_objects(object, state, typeish=typeish)
  File "/home/jonathan/.virtualenvs/.../local/lib/python2.7/site-packages/pprintpp.py", line 280, in _format_nested_objects
    oneline=True)
  File "/home/jonathan/.virtualenvs/.../local/lib/python2.7/site-packages/pprintpp.py", line 310, in _write_nested_real
    object = _sorted(object)
  File "/home/jonathan/.virtualenvs/.../local/lib/python2.7/site-packages/pprintpp.py", line 117, in _sorted
    return sorted(iterable)
TypeError: can only compare to a set

(I didn't had time to look further into this issue.)

PyPI upload broken

Latest PyPI upload (0.2.2) is missing the pprintpp module. ls of the .tar.gz file shows the following:

MANIFEST.in
PKG-INFO
README.rst
pprintpp.egg-info
setup.cfg
setup.py

And installs are therefore breaking.

TypeError on pandas.tslib.NaT

Fails on numpy NaT (not a time):

>>> import pandas

>>> print(pandas.tslib.NaT)
NaT

>>> pprint.pprint(pandas.tslib.NaT)
NaT

>>> pprintpp.pprint(pandas.tslib.NaT)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-151-8d099b04508e> in <module>()
----> 1 pprintpp.pprint(pandas.tslib.NaT)

/Users/danb/miniconda3/lib/python3.5/site-packages/pprintpp/__init__.py in pprint(object, stream, indent, width, depth)
    131     printer = PrettyPrinter(
    132         stream=stream, indent=indent, width=width, depth=depth)
--> 133     printer.pprint(object)
    134
    135 def pformat(object, indent=4, width=80, depth=None):

/Users/danb/miniconda3/lib/python3.5/site-packages/pprintpp/__init__.py in pprint(self, object, state)
    286     def pprint(self, object, state=None):
    287         state = state or self.get_default_state()
--> 288         self._format(object, state)
    289         state.write("\n")
    290

/Users/danb/miniconda3/lib/python3.5/site-packages/pprintpp/__init__.py in _format(self, object, state)
    389         opener_closer_empty = (
    390             self._open_close_empty.get(typ) or
--> 391             self._open_close_empty.get(r)
    392         )
    393         if opener_closer_empty is not None:

TypeError: unhashable type: 'instancemethod'

Does work on numpy NaN (not a number):

>>> import numpy

>>> print(numpy.nan)
nan

>>> pprint.pprint(numpy.nan)
nan

>>> pprintpp.pprint(numpy.nan)
nan

Pretty print collections.defaultdict as if it were a regular dict

pprint.pprint doesn't pretty print collections.defaultdict very nicely. It'd be great if you could at the very least just run them through dict() before printing.

Bonus points for including the fact that it's a defaultdict, and its default function, but that's not really as useful in my experience.

Color in output

If you're rethinking the whole pprint thing right now, how would you feel about adding color to the output?

There is a good library called Clint which makes this super easy.

github code and pypi releases don't match.

I'm trying to port this python module to OpenBSD. The ports system uses pypi to get the software, but the version there (0.4.0) does not correspond with master branch on github, nor does it have an associated tag or release.

That makes the info pretty confusing. For instance tests should depend on parameterized and not nose_parameterized (this commit is not on pypi 8732176).

Could you take a look at that ?

Thank you.

Weird indent

Hi

I got a kinda weird output from pprintpp. Here's the code, it's reading a java properties file and putting it in a "tree" data collection made with defaultdict

# pip install -U pip pyjavaproperties pprintpp pp-ez

from pyjavaproperties import Properties
from collections import defaultdict
import pp

class tree(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

p = Properties()
p.load(open('my.properties'))

data = tree()
for name in p.propertyNames():
    if re.match('^tomcat\d.port',name):
       n = name.split('.')
       data[n[0]][n[2]] = p.getProperty(name)

pp(data)

Here's a relevant piece of properties

tomcat1.port.ajp13=53000
tomcat1.port.http=52100
tomcat1.port.jmx=52200
tomcat1.port.shutdown=59000
tomcat2.port.http=52020
tomcat2.port.jmx=52320
tomcat2.port.shutdown=59020
tomcat3.port.http=52030
tomcat3.port.jmx=52330
tomcat3.port.shutdown=59030
tomcat4.port.http=52040
tomcat4.port.jmx=52340
tomcat4.port.shutdown=59040
tomcat5.port.http=52050
tomcat5.port.jmx=52350
tomcat5.port.shutdown=59050
tomcat6.port.http=52060
tomcat6.port.jmx=52360
tomcat6.port.shutdown=59060

Here's the weird output

{
    'tomcat1': {
        'ajp13': '53000',
        'http': '52100',
        'jmx': '52200',
        'shutdown': '59000',
    },
    'tomcat2': {'http': '52020', 'jmx': '52320', 'shutdown': '59020'},
    'tomcat3': {'http': '52030', 'jmx': '52330', 'shutdown': '59030'},
    'tomcat4': {'http': '52040', 'jmx': '52340', 'shutdown': '59040'},
    'tomcat5': {'http': '52050', 'jmx': '52350', 'shutdown': '59050'},
    'tomcat6': {'http': '52060', 'jmx': '52360', 'shutdown': '59060'},
}

That's good enought for me, but still quite curious!

I'm running centos6's default Python 2.6.6 with pprintpp out of pip

Add `sort_dicts` option

In python 3.8, the sort_dicts option was added (here) and would be great to add that option in this package as well, not only to maintain drop replacement functionality with pprint, but also to add the functionality that argument brings.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.