Module:lib.pretty

Python advanced pretty printer. This pretty printer is intended toreplace the oldpprint python module which does not allow developersto provide their own pretty print callbacks.

This module is based on ruby’sprettyprint.rb library byTanakaAkira.

Example Usage

To directly print the representation of an object usepprint:

fromprettyimportpprintpprint(complex_object)

To get a string of the output usepretty:

fromprettyimportprettystring=pretty(complex_object)

Extending

The pretty library allows developers to add pretty printing rules for theirown objects. This process is straightforward. All you have to do is toadd a_repr_pretty_ method to your object and call the methods on thepretty printer passed:

classMyObject(object):def_repr_pretty_(self,p,cycle):...

Here’s an example for a class with a simple constructor:

classMySimpleObject:def__init__(self,a,b,*,c=None):self.a=aself.b=bself.c=cdef_repr_pretty_(self,p,cycle):ctor=CallExpression.factory(self.__class__.__name__)ifself.cisNone:p.pretty(ctor(a,b))else:p.pretty(ctor(a,b,c=c))

Here is an example implementation of a_repr_pretty_ method for a listsubclass:

classMyList(list):def_repr_pretty_(self,p,cycle):ifcycle:p.text('MyList(...)')else:withp.group(8,'MyList([','])'):foridx,iteminenumerate(self):ifidx:p.text(',')p.breakable()p.pretty(item)

Thecycle parameter isTrue if pretty detected a cycle. Youhave toreact to that or the result is an infinite loop.p.text() just addsnon breaking text to the output,p.breakable() either adds a whitespaceor breaks here. If you pass it an argument it’s used instead of thedefault space.p.pretty prettyprints another object using the pretty printmethod.

The first parameter to thegroup function specifies the extra indentationof the next line. In this example the next item will either be on the sameline (if the items are short enough) or aligned with the right edge of theopening bracket ofMyList.

If you just want to indent something you can use the group functionwithout open / close parameters. You can also use this code:

withp.indent(2):...

Inheritance diagram:

Inheritance diagram of IPython.lib.pretty
copyright:

2007 by Armin Ronacher.Portions (c) 2009 by Robert Kern.

license:

BSD License.

10 Classes

classIPython.lib.pretty.PrettyPrinter(output,max_width=79,newline='\n',max_seq_length=1000)

Bases:_PrettyPrinterBase

Baseclass for theRepresentationPrinter prettyprinter that is used togenerate pretty reprs of objects. Contrary to theRepresentationPrinterthis printer knows nothing about the default pprinters or the_repr_pretty_callback method.

__init__(output,max_width=79,newline='\n',max_seq_length=1000)
begin_group(indent=0,open='')

Begin a group.The first parameter specifies the indentation for the next line (usuallythe width of the opening text), the second the opening text. Allparameters are optional.

break_()

Explicitly insert a newline into the output, maintaining correct indentation.

breakable(sep='')

Add a breakable separator to the output. This does not mean that itwill automatically break here. If no breaking on this position takesplace thesep is inserted which default to one space.

end_group(dedent=0,close='')

End a group. Seebegin_group for more details.

flush()

Flush data that is left in the buffer.

text(obj)

Add literal text to the output.

classIPython.lib.pretty.RepresentationPrinter(output,verbose=False,max_width=79,newline='\n',singleton_pprinters=None,type_pprinters=None,deferred_pprinters=None,max_seq_length=1000)

Bases:PrettyPrinter

Special pretty printer that has apretty method that calls the prettyprinter for a python object.

This class stores processing data onself so you mustnever usethis class in a threaded environment. Always lock it or reinstanciateit.

Instances also have a verbose flag callbacks can access to control theiroutput. For example the default instance repr prints all attributes andmethods that are not prefixed by an underscore if the printer is inverbose mode.

__init__(output,verbose=False,max_width=79,newline='\n',singleton_pprinters=None,type_pprinters=None,deferred_pprinters=None,max_seq_length=1000)
pretty(obj)

Pretty print the given object.

classIPython.lib.pretty.Printable

Bases:object

classIPython.lib.pretty.Text

Bases:Printable

__init__()
classIPython.lib.pretty.Breakable(seq,width,pretty)

Bases:Printable

__init__(seq,width,pretty)
classIPython.lib.pretty.Group(depth)

Bases:Printable

__init__(depth)
classIPython.lib.pretty.GroupQueue(*groups)

Bases:object

__init__(*groups)
classIPython.lib.pretty.RawText(value)

Bases:object

Object such thatp.pretty(RawText(value)) is the same asp.text(value).

An example usage of this would be to show a list as binary numbers, usingp.pretty([RawText(bin(i))foriinintegers]).

__init__(value)
classIPython.lib.pretty.CallExpression(_CallExpression__name,*args,**kwargs)

Bases:object

Object which emits a line-wrapped call expression in the form__name(*args,**kwargs)

__init__(_CallExpression__name,*args,**kwargs)
classIPython.lib.pretty.RawStringLiteral(value)

Bases:object

Wrapper that shows a string with ar prefix

__init__(value)

4 Functions

IPython.lib.pretty.pretty(obj,verbose=False,max_width=79,newline='\n',max_seq_length=1000)

Pretty print the object’s representation.

IPython.lib.pretty.pprint(obj,verbose=False,max_width=79,newline='\n',max_seq_length=1000)

Likepretty but print to stdout.

IPython.lib.pretty.for_type(typ,func)

Add a pretty printer for a given type.

IPython.lib.pretty.for_type_by_name(type_module,type_name,func)

Add a pretty printer for a type specified by the module and name of a typerather than the type object itself.