Printing System

See the Printing section in Tutorial for introduction into printing.

This guide documents the printing system in SymPy and how it works internally.

Printer Class

The main class responsible for printing is Printer (see also its source code):

class sympy.printing.printer.Printer

Generic printer

Its job is to provide infrastructure for implementing new printers easily.

Basically, if you want to implement a printer, all you have to do is:

  1. Subclass Printer.

  2. Define Printer.printmethod in your subclass. If a object has a method with that name, this method will be used for printing.

  3. In your subclass, define _print_<CLASS> methods

    For each class you want to provide printing to, define an appropriate method how to do it. For example if you want a class FOO to be printed in its own way, define _print_FOO:

    def _print_FOO(self, e):

    ...

    this should return how FOO instance e is printed

    Also, if BAR is a subclass of FOO, _print_FOO(bar) will be called for instance of BAR, if no _print_BAR is provided. Thus, usually, we don’t need to provide printing routines for every class we want to support – only generic routine has to be provided for a set of classes.

    A good example for this are functions - for example PrettyPrinter only defines _print_Function, and there is no _print_sin, _print_tan, etc...

    On the other hand, a good printer will probably have to define separate routines for Symbol, Atom, Number, Integral, Limit, etc...

  4. If convenient, override self.emptyPrinter

    This callable will be called to obtain printing result as a last resort, that is when no appropriate print method was found for an expression.

Example of overloading StrPrinter:

from sympy import Basic, Function, Symbol
from sympy.printing.str import StrPrinter

class CustomStrPrinter(StrPrinter):
    """
    Example of how to customize the StrPrinter for both a Sympy class and a
    user defined class subclassed from the Sympy Basic class.
    """

    def _print_Derivative(self, expr):
        """
        Custom printing of the Sympy Derivative class.

        Instead of:

        D(x(t), t) or D(x(t), t, t)

        We will print:

        x'     or     x''

        In this example, expr.args == (x(t), t), and expr.args[0] == x(t), and
        expr.args[0].func == x
        """
        return str(expr.args[0].func) + "'"*len(expr.args[1:])

    def _print_MyClass(self, expr):
        """
        Print the characters of MyClass.s alternatively lower case and upper
        case
        """
        s = ""
        i = 0
        for char in expr.s:
            if i % 2 == 0:
                s += char.lower()
            else:
                s += char.upper()
            i += 1
        return s

# Override the __str__ method of to use CustromStrPrinter
Basic.__str__ = lambda self: CustomStrPrinter().doprint(self)
# Demonstration of CustomStrPrinter:
t = Symbol('t')
x = Function('x')(t)
dxdt = x.diff(t)            # dxdt is a Derivative instance
d2xdt2 = dxdt.diff(t)       # dxdt2 is a Derivative instance
ex = MyClass('I like both lowercase and upper case')

print dxdt
print d2xdt2
print ex

The output of the above code is:

x'
x''
i lIkE BoTh lOwErCaSe aNd uPpEr cAsE

By overriding Basic.__str__, we can customize the printing of anything that is subclassed from Basic.

doprint(expr)
Returns printer’s representation for expr (as a string)
_print(expr, *args)

Internal dispatcher

Tries the following concepts to print an expression:
  1. Let the object print itself if it knows how.
  2. Take the best fitting method defined in the printer.
  3. As fall-back use the emptyPrinter method for the printer.

PrettyPrinter Class

Pretty printing subsystem is implemented in sympy.printing.pretty.pretty by the PrettyPrinter class deriving from Printer. It relies on modules sympy.printing.pretty.stringPict, and sympy.printing.pretty.pretty_symbology for rendering nice-looking formulas.

The module stringPict provides a base class stringPict and a derived class prettyForm that ease the creation and manipulation of formulas that span across multiple lines.

The module pretty_symbology provides primitives to construct 2D shapes (hline, vline, etc) together with a technique to use unicode automatically when possible.

MathMLPrinter

This class is responsible for MathML printing. See sympy.printing.mathml.

More info on mathml content: http://www.w3.org/TR/MathML2/chapter4.html

LatexPrinter

This class implements LaTeX printing. See sympy.printing.latex.

See also the extended LatexPrinter: Extended LaTeXModule for Sympy

Gtk

You can print to a grkmathview widget using the function print_gtk located in sympy.printing.gtk (it requires to have installed gtkmatmatview and libgtkmathview-bin in some systems).

GtkMathView accepts MathML, so this rendering depends on the mathml representation of the expression

Usage:

from sympy import *
print_gtk(x**2 + 2*exp(x**3))

PythonPrinter

This class implements Python printing. Usage:

In [1]: print_python(5*x**3 + sin(x))
x = Symbol('x')
e = sin(x) + 5*x**3

Preview

A useful function is preview:

sympy.printing.preview.preview(expr, output='png', viewer=None, euler=True)

View expression in PNG, DVI, PostScript or PDF form.

This will generate LaTeX representation of the given expression and compile it using available TeX distribution. Then it will run appropriate viewer for the given output format or use the user defined one. If you prefer not to use external viewer then you can use combination of ‘png’ output and ‘pyglet’ viewer. By default png output is generated.

By default pretty Euler fonts are used for typesetting (they were used to typeset the well known “Concrete Mathematics” book). If you prefer default AMS fonts or your system lacks ‘eulervm’ LaTeX package then unset ‘euler’ keyword argument.

To use viewer auto-detection, lets say for ‘png’ output, issue:

>> from sympy import *
>> x, y = symbols("xy")

>> preview(x + y, output='png')

This will choose ‘pyglet by default. To select different one:

>> preview(x + y, output='png', viewer='gimp')

The ‘png’ format is considered special. For all other formats the rules are slightly different. As an example we will take ‘dvi’ output format. If you would run:

>> preview(x + y, output='dvi')

then ‘view’ will look for available ‘dvi’ viewers on your system (predefined in the function, so it will try evince, first, then kdvi and xdvi). If nothing is found you will need to set the viewer explicitly:

>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')

This will skip auto-detection and will run user specified ‘superior-dvi-viewer’. If ‘view’ fails to find it on your system it will gracefully raise an exception.

Currently this depends on pexpect, which is not available for windows.

Table Of Contents

Previous topic

Polynomials Module

Next topic

Plotting

This Page