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

Printing subsystem driver

SymPy’s printing system works the following way: Any expression can be passed to a designated Printer who then is responsible to return an adequate representation of that expression.

The basic concept is the following:
  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.

Some more information how the single concepts work and who should use which:

  1. The object prints itself

    This was the original way of doing printing in sympy. Every class had its own latex, mathml, str and repr methods, but it turned out that it is hard to produce a high quality printer, if all the methods are spread out that far. Therefor all printing code was combined into the different printers, which works great for built-in sympy objects, but not that good for user defined classes where it is inconvenient to patch the printers.

    Nevertheless, to get a fitting representation, the printers look for a specific method in every object, that will be called if it’s available and is then responsible for the representation. The name of that method depends on the specific printer and is defined under Printer.printmethod.

  2. Take the best fitting method defined in the printer.

    The printer loops through expr classes (class + its bases), and tries to dispatch the work to _print_<EXPR_CLASS>

    e.g., suppose we have the following class hierarchy:


    then, for expr=Rational(...), in order to dispatch, we will try calling printer methods as shown in the figure below:

    |-- p._print_Rational(expr)
    |-- p._print_Number(expr)
    |-- p._print_Atom(expr)
    `-- p._print_Basic(expr)

    if ._print_Rational method exists in the printer, then it is called, and the result is returned back.

    otherwise, we proceed with trying Rational bases in the inheritance order.

  3. As fall-back use the emptyPrinter method for the printer.

    As fall-back self.emptyPrinter will be called with the expression. If not defined in the Printer subclass this will be the same as str(expr).

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

class sympy.printing.printer.Printer(settings=None)[source]

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.

Examples of overloading StrPrinter:

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

class CustomStrPrinter(StrPrinter):
    Examples 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
        s = ""
        i = 0
        for char in expr.s:
            if i % 2 == 0:
                s += char.lower()
                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:

i lIkE BoTh lOwErCaSe aNd uPpEr cAsE

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


printmethod = None

Returns printer’s representation for expr (as a string)

_print(expr, *args)[source]

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.
classmethod set_global_settings(**settings)[source]

Set system-wide printing settings.

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.

class sympy.printing.pretty.pretty.PrettyPrinter(settings=None)[source]

Printer, which converts an expression into 2D ASCII-art figure.

printmethod = '_pretty'
sympy.printing.pretty.pretty.pretty(expr, **settings)[source]

Returns a string containing the prettified form of expr.

For information on keyword arguments see pretty_print function.

sympy.printing.pretty.pretty.pretty_print(expr, **settings)[source]

Prints expr in pretty form.

pprint is just a shortcut for this function.

Parameters :

expr : expression

the expression to print

wrap_line : bool, optional

line wrapping enabled/disabled, defaults to True

num_columns : bool, optional

number of columns before line breaking (default to None which reads the terminal width), useful when using SymPy without terminal.

use_unicode : bool or None, optional

use unicode characters, such as the Greek letter pi instead of the string pi.

full_prec : bool or string, optional

use full precision. Default to “auto”

order : bool or string, optional

set to ‘none’ for long expressions if slow; default is None


This class implements C code printing (i.e. it converts Python expressions to strings of C code).


>>> from sympy.printing import print_ccode
>>> from sympy.functions import sin, cos, Abs
>>> from import x
>>> print_ccode(sin(x)**2 + cos(x)**2)
pow(sin(x), 2) + pow(cos(x), 2)
>>> print_ccode(2*x + cos(x), assign_to="result")
result = 2*x + cos(x);
>>> print_ccode(Abs(x**2))
fabs(pow(x, 2))
sympy.printing.ccode.known_functions = {'Abs': [(<function <lambda> at 0x10b5318c0>, 'fabs')], 'ceiling': [(<function <lambda> at 0x10b53af80>, 'ceil')]}
class sympy.printing.ccode.CCodePrinter(settings={})[source]

A printer to convert python expressions to strings of c code

printmethod = '_ccode'
doprint(expr, assign_to=None)[source]

Actually format the expression as C code.


Accepts a string of code or a list of code lines

sympy.printing.ccode.ccode(expr, assign_to=None, **settings)[source]

Converts an expr to a string of c code

Parameters :

expr : sympy.core.Expr

a sympy expression to be converted

precision : optional

the precision for numbers such as pi [default=15]

user_functions : optional

A dictionary where keys are FunctionClass instances and values are there string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples.

human : optional

If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a more programmer-friendly data structure.


>>> from sympy import ccode, symbols, Rational, sin
>>> x, tau = symbols(["x", "tau"])
>>> ccode((2*tau)**Rational(7,2))
'8*sqrt(2)*pow(tau, 7.0/2.0)'
>>> ccode(sin(x), assign_to="s")
's = sin(x);'
sympy.printing.ccode.print_ccode(expr, **settings)[source]

Prints C representation of the given expression.

Fortran Printing

The fcode function translates a sympy expression into Fortran code. The main purpose is to take away the burden of manually translating long mathematical expressions. Therefore the resulting expression should also require no (or very little) manual tweaking to make it compilable. The optional arguments of fcode can be used to fine-tune the behavior of fcode in such a way that manual changes in the result are no longer needed.

sympy.printing.fcode.fcode(expr, **settings)[source]

Converts an expr to a string of Fortran 77 code

Parameters :

expr : sympy.core.Expr

a sympy expression to be converted

assign_to : optional

When given, the argument is used as the name of the variable to which the Fortran expression is assigned. (This is helpful in case of line-wrapping.)

precision : optional

the precision for numbers such as pi [default=15]

user_functions : optional

A dictionary where keys are FunctionClass instances and values are there string representations.

human : optional

If True, the result is a single string that may contain some parameter statements for the number symbols. If False, the same information is returned in a more programmer-friendly data structure.

source_format : optional

The source format can be either ‘fixed’ or ‘free’. [default=’fixed’]


>>> from sympy import fcode, symbols, Rational, pi, sin
>>> x, tau = symbols('x,tau')
>>> fcode((2*tau)**Rational(7,2))
'      8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)'
>>> fcode(sin(x), assign_to="s")
'      s = sin(x)'
>>> print(fcode(pi))
      parameter (pi = 3.14159265358979d0)
sympy.printing.fcode.print_fcode(expr, **settings)[source]

Prints the Fortran representation of the given expression.

See fcode for the meaning of the optional arguments.

class sympy.printing.fcode.FCodePrinter(settings=None)[source]

A printer to convert sympy expressions to strings of Fortran code

printmethod = '_fcode'

Returns Fortran code for expr (as a string)


Accepts a string of code or a list of code lines

Two basic examples:

>>> from sympy import *
>>> x = symbols("x")
>>> fcode(sqrt(1-x**2))
'      sqrt(-x**2 + 1)'
>>> fcode((3 + 4*I)/(1 - conjugate(x)))
'      (cmplx(3,4))/(-conjg(x) + 1)'

An example where line wrapping is required:

>>> expr = sqrt(1-x**2).series(x,n=20).removeO()
>>> print(fcode(expr))
      -715*x**18/65536 - 429*x**16/32768 - 33*x**14/2048 - 21*x**12/1024
     @ - 7*x**10/256 - 5*x**8/128 - x**6/16 - x**4/8 - x**2/2 + 1

In case of line wrapping, it is handy to include the assignment so that lines are wrapped properly when the assignment part is added.

>>> print(fcode(expr, assign_to="var"))
      var = -715*x**18/65536 - 429*x**16/32768 - 33*x**14/2048 - 21*x**
     @ 12/1024 - 7*x**10/256 - 5*x**8/128 - x**6/16 - x**4/8 - x**2/2 +
     @ 1

For piecewise functions, the assign_to option is mandatory:

>>> print(fcode(Piecewise((x,x<1),(x**2,True)), assign_to="var"))
      if (x < 1) then
        var = x
        var = x**2
      end if

Note that only top-level piecewise functions are supported due to the lack of a conditional operator in Fortran. Nested piecewise functions would require the introduction of temporary variables, which is a type of expression manipulation that goes beyond the scope of fcode.

Loops are generated if there are Indexed objects in the expression. This also requires use of the assign_to option.

>>> A, B = list(map(IndexedBase, ['A', 'B']))
>>> m = Symbol('m', integer=True)
>>> i = Idx('i', m)
>>> print(fcode(2*B[i], assign_to=A[i]))
    do i = 1, m
        A(i) = 2*B(i)
    end do

Repeated indices in an expression with Indexed objects are interpreted as summation. For instance, code for the trace of a matrix can be generated with

>>> print(fcode(A[i, i], assign_to=x))
      x = 0
      do i = 1, m
          x = x + A(i, i)
      end do

By default, number symbols such as pi and E are detected and defined as Fortran parameters. The precision of the constants can be tuned with the precision argument. Parameter definitions are easily avoided using the N function.

>>> print(fcode(x - pi**2 - E))
      parameter (E = 2.71828182845905d0)
      parameter (pi = 3.14159265358979d0)
      x - pi**2 - E
>>> print(fcode(x - pi**2 - E, precision=25))
      parameter (E = 2.718281828459045235360287d0)
      parameter (pi = 3.141592653589793238462643d0)
      x - pi**2 - E
>>> print(fcode(N(x - pi**2, 25)))
      x - 9.869604401089358618834491d0

When some functions are not part of the Fortran standard, it might be desirable to introduce the names of user-defined functions in the Fortran expression.

>>> print(fcode(1 - gamma(x)**2, user_functions={gamma: 'mygamma'}))
      -mygamma(x)**2 + 1

However, when the user_functions argument is not provided, fcode attempts to use a reasonable default and adds a comment to inform the user of the issue.

>>> print(fcode(1 - gamma(x)**2))
C     Not Fortran:
C     gamma(x)
      -gamma(x)**2 + 1

By default the output is human readable code, ready for copy and paste. With the option human=False, the return value is suitable for post-processing with source code generators that write routines with multiple instructions. The return value is a three-tuple containing: (i) a set of number symbols that must be defined as ‘Fortran parameters’, (ii) a list functions that can not be translated in pure Fortran and (iii) a string of Fortran code. A few examples:

>>> fcode(1 - gamma(x)**2, human=False)
(set(), set([gamma(x)]), '      -gamma(x)**2 + 1')
>>> fcode(1 - sin(x)**2, human=False)
(set(), set(), '      -sin(x)**2 + 1')
>>> fcode(x - pi**2, human=False)
(set([(pi, '3.14159265358979d0')]), set(), '      x - pi**2')


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.


from sympy import *
print_gtk(x**2 + 2*exp(x**3))
sympy.printing.gtk.print_gtk(x, start_viewer=True)[source]

Print to Gtkmathview, a gtk widget capable of rendering MathML.

Needs libgtkmathview-bin


This classes implements printing to strings that can be used by the sympy.utilities.lambdify.lambdify() function.

class sympy.printing.lambdarepr.LambdaPrinter(settings=None)[source]

This printer converts expressions into strings that can be used by lambdify.

printmethod = '_sympystr'
sympy.printing.lambdarepr.lambdarepr(expr, **settings)[source]

Returns a string usable for lambdifying.


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

See also the extended LatexPrinter: Extended LaTeXModule for SymPy

sympy.printing.latex.accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan', 'theta', 'beta', 'alpha', 'gamma', 'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec', 'csc', 'cot', 'coth', 're', 'im', 'frac', 'root', 'arg', 'zeta', 'psi']

list() -> new empty list list(iterable) -> new list initialized from iterable’s items

class sympy.printing.latex.LatexPrinter(settings=None)[source]
printmethod = '_latex'
sympy.printing.latex.latex(expr, **settings)[source]

Convert the given expression to LaTeX representation.

>>> from sympy import latex, sin, asin, Matrix, Rational
>>> from import x, y, mu, tau
>>> latex((2*tau)**Rational(7,2))
'8 \\sqrt{2} \\tau^{\\frac{7}{2}}'

order: Any of the supported monomial orderings (currently “lex”, “grlex”, or “grevlex”), “old”, and “none”. This parameter does nothing for Mul objects. Setting order to “old” uses the compatibility ordering for Add defined in Printer. For very large expressions, set the ‘order’ keyword to ‘none’ if speed is a concern.

mode: Specifies how the generated code will be delimited. ‘mode’ can be one of ‘plain’, ‘inline’, ‘equation’ or ‘equation*’. If ‘mode’ is set to ‘plain’, then the resulting code will not be delimited at all (this is the default). If ‘mode’ is set to ‘inline’ then inline LaTeX $ $ will be used. If ‘mode’ is set to ‘equation’ or ‘equation*’, the resulting code will be enclosed in the ‘equation’ or ‘equation*’ environment (remember to import ‘amsmath’ for ‘equation*’), unless the ‘itex’ option is set. In the latter case, the $$ $$ syntax is used.

>>> latex((2*mu)**Rational(7,2), mode='plain')
'8 \\sqrt{2} \\mu^{\\frac{7}{2}}'
>>> latex((2*tau)**Rational(7,2), mode='inline')
'$8 \\sqrt{2} \\tau^{\\frac{7}{2}}$'
>>> latex((2*mu)**Rational(7,2), mode='equation*')
'\\begin{equation*}8 \\sqrt{2} \\mu^{\\frac{7}{2}}\\end{equation*}'
>>> latex((2*mu)**Rational(7,2), mode='equation')
'\\begin{equation}8 \\sqrt{2} \\mu^{\\frac{7}{2}}\\end{equation}'

itex: Specifies if itex-specific syntax is used, including emitting $$ $$.

>>> latex((2*mu)**Rational(7,2), mode='equation', itex=True)
'$$8 \\sqrt{2} \\mu^{\\frac{7}{2}}$$'

fold_frac_powers: Emit “^{p/q}” instead of “^{frac{p}{q}}” for fractional powers.

>>> latex((2*tau)**Rational(7,2), fold_frac_powers=True)
'8 \\sqrt{2} \\tau^{7/2}'

fold_func_brackets: Fold function brackets where applicable.

>>> latex((2*tau)**sin(Rational(7,2)))
'\\left(2 \\tau\\right)^{\\sin{\\left (\\frac{7}{2} \\right )}}'
>>> latex((2*tau)**sin(Rational(7,2)), fold_func_brackets = True)
'\\left(2 \\tau\\right)^{\\sin {\\frac{7}{2}}}'

mul_symbol: The symbol to use for multiplication. Can be one of None, “ldot”, “dot”, or “times”.

>>> latex((2*tau)**sin(Rational(7,2)), mul_symbol="times")
'\\left(2 \\times \\tau\\right)^{\\sin{\\left (\\frac{7}{2} \\right )}}'

inv_trig_style: How inverse trig functions should be displayed. Can be one of “abbreviated”, “full”, or “power”. Defaults to “abbreviated”.

>>> latex(asin(Rational(7,2)))
'\\operatorname{asin}{\\left (\\frac{7}{2} \\right )}'
>>> latex(asin(Rational(7,2)), inv_trig_style="full")
'\\arcsin{\\left (\\frac{7}{2} \\right )}'
>>> latex(asin(Rational(7,2)), inv_trig_style="power")
'\\sin^{-1}{\\left (\\frac{7}{2} \\right )}'

mat_str: Which matrix environment string to emit. “smallmatrix”, “bmatrix”, etc. Defaults to “smallmatrix”.

>>> latex(Matrix(2, 1, [x, y]), mat_str = "array")

mat_delim: The delimiter to wrap around matrices. Can be one of “[”, “(”, or the empty string. Defaults to “[”.

>>> latex(Matrix(2, 1, [x, y]), mat_delim="(")

symbol_names: Dictionary of symbols and the custom strings they should be emitted as.

>>> latex(x**2, symbol_names={x:'x_i'})

Besides all Basic based expressions, you can recursively convert Python containers (lists, tuples and dicts) and also SymPy matrices:

>>> latex([2/x, y], mode='inline')
'$\\begin{bmatrix}\\frac{2}{x}, & y\\end{bmatrix}$'
sympy.printing.latex.print_latex(expr, **settings)[source]

Prints LaTeX representation of the given expression.


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

More info on mathml content:

class sympy.printing.mathml.MathMLPrinter(settings=None)[source]

Prints an expression to the MathML markup language

Whenever possible tries to use Content markup and not Presentation markup.


printmethod = '_mathml'

Prints the expression as MathML.


Returns the MathML tag for an expression.

sympy.printing.mathml.mathml(expr, **settings)[source]

Returns the MathML representation of expr

sympy.printing.mathml.print_mathml(expr, **settings)[source]

Prints a pretty representation of the MathML code for expr


>>> ##
>>> from sympy.printing.mathml import print_mathml
>>> from import x
>>> print_mathml(x+1) 


This class implements Python printing. Usage:

>>> from sympy import print_python, sin
>>> from import x

>>> print_python(5*x**3 + sin(x))
x = Symbol('x')
e = 5*x**3 + sin(x)


This printer generates executable code. This code satisfies the identity eval(srepr(expr))=expr.

class sympy.printing.repr.ReprPrinter(settings=None)[source]
printmethod = '_sympyrepr'

The fallback printer.

reprify(args, sep)[source]

Prints each item in \(args\) and joins them with \(sep\).

sympy.printing.repr.srepr(expr, **settings)[source]

return expr in repr form


This module generates readable representations of SymPy expressions.

class sympy.printing.str.StrPrinter(settings=None)[source]
printmethod = '_sympystr'
sympy.printing.str.sstrrepr(expr, **settings)[source]

return expr in mixed str/repr form

i.e. strings are returned in repr form with quotes, and everything else is returned in str form.

This function could be useful for hooking into sys.displayhook

Tree Printing

The functions in this module create a representation of an expression as a tree.


Prettyprints systems of nodes.


>>> from sympy.printing.tree import pprint_nodes
>>> print(pprint_nodes(["a", "b1\nb2", "c"]))
| b2

Returns an information about the “node”.

This includes class name, string representation and assumptions.


Returns a tree representation of “node” as a string.

It uses print_node() together with pprint_nodes() on node.args recursively.

See also: print_tree()


Prints a tree representation of “node”.


>>> from sympy.printing import print_tree
>>> from import x
>>> print_tree(x**2) 
Pow: x**2
+-Symbol: x
| comparable: False
+-Integer: 2
  real: True
  nonzero: True
  comparable: True
  commutative: True
  infinitesimal: False
  unbounded: False
  noninteger: False
  zero: False
  complex: True
  bounded: True
  rational: True
  integer: True
  imaginary: False
  finite: True
  irrational: False

See also: tree()


A useful function is preview:

sympy.printing.preview.preview(expr, output='png', viewer=None, euler=True, packages=(), **latex_settings)[source]

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

If the expr argument is an expression, it will be exported to LaTeX and then compiled using available the TeX distribution. The first argument, ‘expr’, may also be a LaTeX string. The function will then run the appropriate viewer for the given output format or use the user defined one. 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). For that to work, you need the ‘eulervm.sty’ LaTeX style (in Debian/Ubuntu, install the texlive-fonts-extra package). If you prefer default AMS fonts or your system lacks ‘eulervm’ LaTeX package then unset the ‘euler’ keyword argument.

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

>>> from sympy import symbols, preview, Symbol
>>> x, y = symbols("x,y")
>>> preview(x + y, output='png') 

This will choose ‘pyglet’ by default. To select a different one, do

>>> 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. You may also enter ‘file’ for the viewer argument. Doing so will cause this function to return a file object in read-only mode.

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

Additional keyword args will be passed to the latex call, e.g., the symbol_names flag.

>>> phidd = Symbol('phidd')
>>> preview(phidd, symbol_names={phidd:r'\ddot{\varphi}'}) 

Implementation - Helper Classes/Functions


Split a symbol name into a name, superscripts and subscripts

The first part of the symbol name is considered to be its actual ‘name’, followed by super- and subscripts. Each superscript is preceded with a “^” character or by “__”. Each subscript is preceded by a “_” character. The three return values are the actual name, a list with superscripts and a list with subscripts.

>>> from sympy.printing.conventions import split_super_sub
>>> split_super_sub('a_x^1')
('a', ['1'], ['x'])
>>> split_super_sub('var_sub1__sup_sub2')
('var', ['sup'], ['sub1', 'sub2'])


This class is a base class for other classes that implement code-printing functionality, and additionally lists a number of functions that cannot be easily translated to C or Fortran.

class sympy.printing.codeprinter.CodePrinter(settings=None)[source]

The base class for code-printing subclasses.

printmethod = '_sympystr'
exception sympy.printing.codeprinter.AssignmentError[source]

Raised if an assignment variable for a loop is missing.


sympy.printing.precedence.PRECEDENCE = {'Pow': 60, 'Not': 100, 'Lambda': 1, 'Add': 40, 'Relational': 20, 'And': 30, 'Atom': 1000, 'Mul': 50, 'Or': 20}

Default precedence values for some basic types.

sympy.printing.precedence.PRECEDENCE_VALUES = {'Pow': 60, 'Not': 100, 'Sub': 40, 'NegativeInfinity': 40, 'factorial2': 60, 'Add': 40, 'Relational': 20, 'And': 30, 'factorial': 60, 'Or': 20}

A dictionary assigning precedence values to certain classes. These values are treated like they were inherited, so not every single class has to be named here.

sympy.printing.precedence.PRECEDENCE_FUNCTIONS = {'Float': <function precedence_Float at 0x10b1e7a70>, 'Integer': <function precedence_Integer at 0x10b1e79e0>, 'Mul': <function precedence_Mul at 0x10b1e78c0>, 'Rational': <function precedence_Rational at 0x10b1e7950>}

Sometimes it’s not enough to assign a fixed precedence value to a class. Then a function can be inserted in this dictionary that takes an instance of this class as argument and returns the appropriate precedence value.


Returns the precedence of a given object.

Pretty-Printing Implementation Helpers


unicode character by name or None if not found


Set whether pretty-printer should use unicode by default


See if unicode output is available and leverage it if possible


call str or unicode depending on current mode

The following two functions return the Unicode version of the inputted Greek letter.

sympy.printing.pretty.pretty_symbology.greek_letters = ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lamda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']

list() -> new empty list list(iterable) -> new list initialized from iterable’s items

sympy.printing.pretty.pretty_symbology.greek = {'lamda': ('λ', 'Λ'), 'upsilon': ('υ', 'Υ'), 'sigma': ('σ', 'Σ'), 'delta': ('δ', 'Δ'), 'xi': ('ξ', 'Ξ'), 'theta': ('θ', 'Θ'), 'lambda': ('λ', 'Λ'), 'omega': ('ω', 'Ω'), 'psi': ('ψ', 'Ψ'), 'phi': ('φ', 'Φ'), 'gamma': ('γ', 'Γ'), 'iota': ('ι', 'Ι'), 'zeta': ('ζ', 'Ζ'), 'chi': ('χ', 'Χ'), 'eta': ('η', 'Η'), 'beta': ('β', 'Β'), 'rho': ('ρ', 'Ρ'), 'alpha': ('α', 'Α'), 'mu': ('μ', 'Μ'), 'nu': ('ν', 'Ν'), 'omicron': ('ο', 'Ο'), 'pi': ('π', 'Π'), 'epsilon': ('ε', 'Ε'), 'tau': ('τ', 'Τ'), 'kappa': ('κ', 'Κ')}
sympy.printing.pretty.pretty_symbology.digit_2txt = {'8': 'EIGHT', '9': 'NINE', '2': 'TWO', '3': 'THREE', '0': 'ZERO', '1': 'ONE', '6': 'SIX', '7': 'SEVEN', '4': 'FOUR', '5': 'FIVE'}
sympy.printing.pretty.pretty_symbology.symb_2txt = {'+': 'PLUS SIGN', '(': 'LEFT PARENTHESIS', ')': 'RIGHT PARENTHESIS', '-': 'MINUS', '=': 'EQUALS SIGN', ']': 'RIGHT SQUARE BRACKET', '{': 'LEFT CURLY BRACKET', '[': 'LEFT SQUARE BRACKET', 'sum': 'SUMMATION', 'int': 'INTEGRAL', '}': 'RIGHT CURLY BRACKET', '{}': 'CURLY BRACKET'}

The following functions return the Unicode subscript/superscript version of the character.

sympy.printing.pretty.pretty_symbology.sub = {'+': '₊', '(': '₍', 'i': 'ᵢ', 'o': 'ₒ', '-': '₋', '=': '₌', 'a': 'ₐ', 'e': 'ₑ', 'r': 'ᵣ', 'x': 'ₓ', '9': '₉', 'phi': 'ᵩ', '2': '₂', '3': '₃', '0': '₀', '1': '₁', '6': '₆', '7': '₇', '4': '₄', '5': '₅', ')': '₎', 'chi': 'ᵪ', 'beta': 'ᵦ', '8': '₈', 'gamma': 'ᵧ', 'v': 'ᵥ', 'u': 'ᵤ', 'rho': 'ᵨ'}
sympy.printing.pretty.pretty_symbology.sup = {')': '⁾', '+': '⁺', '(': '⁽', 'i': 'ⁱ', 'n': 'ⁿ', '-': '⁻', '8': '⁸', '9': '⁹', '=': '⁼', '2': '²', '3': '³', '0': '⁰', '1': '¹', '6': '⁶', '7': '⁷', '4': '⁴', '5': '⁵'}

The following functions return Unicode vertical objects.

sympy.printing.pretty.pretty_symbology.xobj(symb, length)[source]

Construct spatial object of given length.

return: [] of equal-length strings

sympy.printing.pretty.pretty_symbology.vobj(symb, height)[source]

Construct vertical object of a given height

see: xobj

sympy.printing.pretty.pretty_symbology.hobj(symb, width)[source]

Construct horizontal object of a given width

see: xobj

The following constants are for rendering roots and fractions.

sympy.printing.pretty.pretty_symbology.root = {2: '√', 3: '∛', 4: '∜'}
sympy.printing.pretty.pretty_symbology.frac = {(1, 2): '½', (1, 3): '⅓', (5, 6): '⅚', (7, 8): '⅞', (1, 4): '¼', (3, 8): '⅜', (1, 5): '⅕', (1, 8): '⅛', (2, 3): '⅔', (4, 5): '⅘', (1, 6): '⅙', (2, 5): '⅖', (3, 4): '¾', (5, 8): '⅝', (3, 5): '⅗'}

The following constants/functions are for rendering atoms and symbols.


get symbology for a ‘character’

sympy.printing.pretty.pretty_symbology.atoms_table = {'Naturals': 'ℕ', 'Intersection': '∩', 'EmptySet': '∅', 'ImaginaryUnit': 'ⅈ', 'Pi': 'π', 'Exp1': 'ℯ', 'Integers': 'ℤ', 'Union': '∪', 'Reals': 'ℝ', 'NegativeInfinity': '-∞', 'Infinity': '∞'}
sympy.printing.pretty.pretty_symbology.pretty_atom(atom_name, default=None)[source]

return pretty representation of an atom


return pretty representation of a symbol


Return a stylised drawing of the letter letter, together with information on how to put annotations (super- and subscripts to the left and to the right) on it.

See functions _print_meijerg, _print_hyper on how to use this information.

Prettyprinter by Jurjen Bos. (I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay). All objects have a method that create a “stringPict”, that can be used in the str method for pretty printing.

Updates by Jason gedge (email <my last name> at cs mun ca)
  • terminal_string() method
  • minor fixes and changes (mostly to prettyForm)
  • Allow left/center/right alignment options for above/below and top/center/bottom alignment options for left/right
class sympy.printing.pretty.stringpict.stringPict(s, baseline=0)[source]

An ASCII picture. The pictures are represented as a list of equal length strings.


Put pictures above this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of bottom picture.


Put pictures under this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of top picture


>>> from sympy.printing.pretty.stringpict import stringPict
>>> print(stringPict("x+3").below(stringPict.LINE, '3')[0]) 

The height of the picture in characters.


Put pictures (left to right) at left. Returns string, baseline arguments for stringPict.


Precede object by a slash of the proper size.

static next(*args)[source]

Put a string of stringPicts next to each other. Returns string, baseline arguments for stringPict.

parens(left='(', right=')', ifascii_nougly=False)[source]

Put parentheses around self. Returns string, baseline arguments for stringPict.

left or right can be None or empty string which means ‘no paren from that side’

render(*args, **kwargs)[source]

Return the string form of self.

Unless the argument line_break is set to False, it will break the expression in a form that can be printed on the terminal without being broken up.


Put pictures next to this one. Returns string, baseline arguments for stringPict. (Multiline) strings are allowed, and are given a baseline of 0.


>>> from sympy.printing.pretty.stringpict import stringPict
>>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0])
10 + -

Produce a nice root symbol. Produces ugly results for big n inserts.

static stack(*args)[source]

Put pictures on top of each other, from top to bottom. Returns string, baseline arguments for stringPict. The baseline is the baseline of the second picture. Everything is centered. Baseline is the baseline of the second picture. Strings are allowed. The special value stringPict.LINE is a row of ‘-‘ extended to the width.


Return the terminal width if possible, otherwise return 0.


The width of the picture in characters.

class sympy.printing.pretty.stringpict.prettyForm(s, baseline=0, binding=0, str=None)[source]

Extension of the stringPict class that knows about basic math applications, optimizing double minus signs.

“Binding” is interpreted as follows:

ATOM this is an atom: never needs to be parenthesized
FUNC this is a function application: parenthesize if added (?)
DIV  this is a division: make wider division if divided
POW  this is a power: only parenthesize if exponent
MUL  this is a multiplication: parenthesize if powered
ADD  this is an addition: parenthesize if multiplied or powered
NEG  this is a negative number: optimize if added, parenthesize if multiplied or powered
static apply(function, *args)[source]

Functions of one or more variables.