Sage 9.1 Reference Manual: The Sage Command Line: Release 9.1
Sage 9.1 Reference Manual: The Sage Command Line: Release 9.1
1 Running Sage 3
1.1 Invoking Sage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Sage startup scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Environment variables used by Sage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 Relevant environment variables for other packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.5 Interactively tracing execution of a command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2 Preparsing 11
2.1 The Sage Preparser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4 Pretty Printing 35
4.1 IPython Displayhook Formatters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2 The Sage pretty printer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.3 Representations of objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.4 Utility functions for pretty-printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6 Miscellaneous 91
6.1 Sage’s IPython Modifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.2 Sage’s IPython Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.3 Magics for each of the Sage interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
6.4 Interacts for the Sage Jupyter notebook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
6.5 Widgets to be used for the Sage Jupyter notebook . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
6.6 Functions to construct widgets, based on the old SageNB interface. . . . . . . . . . . . . . . . . . . 113
i
6.7 Installing the SageMath Jupyter Kernel and Extensions . . . . . . . . . . . . . . . . . . . . . . . . . 119
6.8 The Sage ZMQ Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
6.9 Tests for the IPython integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
6.10 HTML Generator for JSmol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
6.11 Sage Wrapper for Bitmap Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
6.12 The Sage Input Hook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Index 137
ii
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
The Sage Read-Eval-Print-Loop (REPL) is based on IPython. In this document, you’ll find how the IPython integration
works. You should also be familiar with the documentation for IPython.
For more details about using the Sage command line, see the Sage tutorial.
CONTENTS 1
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
2 CONTENTS
CHAPTER
ONE
RUNNING SAGE
To run Sage, you basically just need to type sage from the command-line prompt to start the Sage interpreter. See
the Sage Installation Guide for information about making sure your $PATH is set correctly, etc.
• file.[sage|py|spyx] – run the given .sage, .py or .spyx files (as in sage my_file.sage)
• -h, -?, --help – print a short help message
• -v, --version – print the Sage version
• --advanced – print (essentially this) list of Sage options
• -c cmd – evaluate cmd as sage code. For example, sage -c 'print(factor(35))' will print “5 * 7”.
• --preparse file.sage – preparse file.sage, a file of Sage code, and produce the corresponding
Python file file.sage.py. See the Sage tutorial for more about preparsing and the differences between Sage
and Python.
• -q – quiet; start with no banner
• --grep [options] <string> – grep through all the Sage library code for string. Any options will
get passed to the “grep” command; for example, sage --grep -i epstein will search for epstein,
and the -i flag tells grep to ignore case when searching. Note that while running Sage, you can also use the
function search_src to accomplish the same thing.
• --grepdoc [options] <string> – grep through all the Sage documentation for string. Note that
while running Sage, you can also use the function search_doc to accomplish the same thing.
• --min [...] – do not populate global namespace (must be first option)
• -gthread, -qthread, -q4thread, -wthread, -pylab – pass the option through to IPython
• --nodotsage – run Sage without using the user’s .sage directory: create and use a temporary .sage
directory instead. Warning: notebooks are stored in the .sage directory, so any notebooks created while
running with --nodotsage will be temporary also.
3
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
• -n [...], --notebook=[...] – start the notebook, valid options are default, sagenb, jupyter
and export (see the output of sage --notebook --help for more details and examples of how to pass
optional arguments)
• -bn [...], --build-and-notebook [...] – build the Sage library (as by running sage -b) then
start the Sage notebook
• --inotebook [...] – start the insecure Sage notebook
• -i [options] [packages] – install the given Sage packages (unless they are already installed); if no
packages are given, print a list of all installed packages. Options:
– -c – run the packages’ test suites, overriding the settings of SAGE_CHECK and
SAGE_CHECK_PACKAGES.
– -f – force build: install the packages even if they are already installed.
– -s – do not delete the spkg/build directories after a successful build – useful for debugging.
• -f [options] [packages] – shortcut for -i -f: force build of the given Sage packages.
• --info [packages] – display the SPKG.txt file of the given Sage packages.
• --standard – list all standard packages that can be installed
• --optional – list all optional packages that can be installed
• --experimental – list all experimental packages that can be installed
• --upgrade [url] – download, build and install standard packages from given url. If url not given, auto-
matically selects a suitable mirror. If url=’ask’, it lets you select the mirror.
Documentation
• --docbuild [options] document (format | command) – build or return information about the
Sage documentation.
– document – name of the document to build
– format – document output format
– command – document-specific command
A document and either a format or a command are required, unless a list of one or more of these is
requested.
Options:
– help, -h, --help – print a help message
– -H, --help-all – print an extended help message, including the output from the options -h, -D, -F,
-C all, and a short list of examples.
– -D, --documents – list all available documents
– -F, --formats – list all output formats
– -C DOC, --commands=DOC – list all commands for document DOC; use -C all to list all
– -i, --inherited – include inherited members in reference manual; may be slow, may fail for PDF
output
– -u, --underscore – include variables prefixed with _ in reference manual; may be slow, may fail for
PDF output
– -j, --jsmath – render math using jsMath; formats: html, json, pickle, web
– --no-pdf-links – do not include PDF links in document website; formats: html, json, pickle,
web
– --check-nested – check picklability of nested classes in document reference
– -N, --no-colors – do not color output; does not affect children
– -q, --quiet – work quietly; same as --verbose=0
– -v LEVEL, --verbose=LEVEL – report progress at level 0 (quiet), 1 (normal), 2 (info), or 3 (debug);
does not affect children
Advanced – use these options with care:
– -S OPTS, --sphinx-opts=OPTS – pass comma-separated OPTS to sphinx-build
– -U, --update-mtimes – before building reference manual, update modification times for auto-
generated ReST files
• --pkg dir – create the Sage package dir.spkg from the directory dir
• --pkg_nc dir – as --pkg, but do not compress the package
• --merge – run Sage’s automatic merge and test script
• --sdist – build a source distribution of Sage
There are two kinds of startup scripts that Sage reads when starting:
The bash shell script $DOT_SAGE/sagerc (with the default value of DOT_SAGE, this is ~/.sage/sagerc)
is read by $SAGE_ROOT/spkg/bin/sage-env after Sage has set its environment variables. It can be used to
override some of the environment variables determined by Sage, or it can contain other shell commands like creating
directories. This script is sourced not only when running Sage itself, but also when running any of the subcommands
(like sage --python, sage -b or sage -i <package>). In particular, setting PS1 here overrides the default
prompt for the Sage shells sage --buildsh and sage --sh.
Note: This script is run with the Sage directories in its PATH, so executing git for example will run the Git inside
Sage.
The default location of this file can be changed using the environment variable SAGE_RC_FILE.
The Sage script $DOT_SAGE/init.sage (with the default value of DOT_SAGE, this is ~/.sage/init.sage)
contains Sage commands to be executed every time Sage starts. If you want symbolic variables y and z in every Sage
session, you could put
var('y, z')
in this file.
The default location of this file can be changed using the environment variable SAGE_STARTUP_FILE.
Sage uses several environment variables when running. These all have sensible default values, so many users won’t
need to set any of these. (There are also variables used to compile Sage; see the Sage Installation Guide for more about
those.)
• DOT_SAGE – this is the directory, to which the user has read and write access, where Sage stores a number of
files. The default location is ~/.sage/, but you can change that by setting this variable.
• SAGE_RC_FILE – a shell script which is sourced after Sage has determined its environment variables. This
script is executed before starting Sage or any of its subcommands (like sage -i <package>). The default
value is $DOT_SAGE/sagerc.
• SAGE_STARTUP_FILE – a file including commands to be executed every time Sage starts. The default value
is $DOT_SAGE/init.sage.
• SAGE_SERVER – only used for installing packages. Alternative mirror from which to download sources, see
the Installation Guide for details.
• BROWSER – on most platforms, Sage will detect the command to run a web browser, but if this doesn’t seem to
work on your machine, set this variable to the appropriate command.
This is a non-exhaustive list of environment variables which influence some package contained within the SageMath
distribution.
In many cases, SageMath uses a custom default value if the variable is not set, which is not the same default that the
system-wide package would use. So, if you would like to use your system-wide configuration, you need to explicitly
set the environment variable to the system-wide default.
• IPYTHONDIR – directory where the configuration of IPython is stored. By default, this is some directory inside
DOT_SAGE. See http://ipython.readthedocs.io/en/stable/development/config.html for more information.
• JUPYTER_CONFIG_DIR – directory where the configuration of Jupyter is stored. By default, this is some di-
rectory inside DOT_SAGE. See http://jupyter.readthedocs.io/en/latest/projects/jupyter-directories.html for more
information.
• MPLCONFIGDIR – directory where the configuration of Matplotlib is stored. See https://matplotlib.
org/faq/environment_variables_faq.html#envvar-MPLCONFIGDIR By default, this is some directory inside
DOT_SAGE.
sage.misc.trace.trace(code, preparse=True)
Evaluate Sage code using the interactive tracer and return the result. The string code must be a valid expression
enclosed in quotes (no assignments - the result of the expression is returned). In the Sage notebook this just raises
a NotImplementedException.
INPUT:
• code - str
• preparse - bool (default: True); if True, run expression through the Sage preparser.
REMARKS: This function is extremely powerful! For example, if you want to step through each line of execu-
tion of, e.g., factor(100), type
then at the (Pdb) prompt type s (or step), then press return over and over to step through every line of Python
that is called in the course of the above computation. Type ? at any time for help on how to use the debugger
(e.g., l lists 11 lines around the current line; bt gives a back trace, etc.).
Setting a break point: If you have some code in a file and would like to drop into the debugger at a given point,
put the following code at that point in the file:
import pdb; pdb.set_trace()
For an article on how to use the Python debugger, see http://www.onlamp.com/pub/a/python/2005/09/01/
debugger.html
TWO
PREPARSING
Sage commands are “preparsed” to valid Python syntax. This allows for example to support the R.<x> = QQ[]
syntax.
AUTHORS:
• William Stein (2006-02-19)
– Fixed bug when loading .py files.
• William Stein (2006-03-09)
– Fixed crash in parsing exponentials.
– Precision of real literals now determined by digits of input (like Mathematica).
• Joe Wetherell (2006-04-14)
– Added MAGMA-style constructor preparsing.
• Bobby Moretti (2007-01-25)
– Added preliminary function assignment notation.
• Robert Bradshaw (2007-09-19)
– Added strip_string_literals, containing_block utility functions. Arrr!
– Added [1,2,..,n] notation.
• Robert Bradshaw (2008-01-04)
– Implicit multiplication (off by default).
• Robert Bradshaw (2008-09-23)
– Factor out constants.
• Robert Bradshaw (2000-01)
– Simplify preparser by making it modular and using regular expressions.
– Bug fixes, complex numbers, and binary input.
EXAMPLES:
Preparsing:
11
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
sage: preparse('2/3')
'Integer(2)/Integer(3)'
sage: preparse('2.5')
"RealNumber('2.5')"
sage: preparse('2^3')
'Integer(2)**Integer(3)'
sage: preparse('a^b') # exponent
'a**b'
sage: preparse('a**b')
'a**b'
sage: preparse('G.0') # generator
'G.gen(0)'
sage: preparse('a = 939393R') # raw
'a = 939393'
sage: implicit_multiplication(True)
sage: preparse('a b c in L') # implicit multiplication
'a*b*c in L'
sage: preparse('2e3x + 3exp(y)')
"RealNumber('2e3')*x + Integer(3)*exp(y)"
A string with escaped quotes in it (the point here is that the preparser doesn’t get confused by the internal quotes):
A hex literal:
sage: preparse('0x2e3')
'Integer(0x2e3)'
sage: 0xA
10
sage: 0xe
14
sage: type(0xa1)
<type 'sage.rings.integer.Integer'>
sage: type(0xa1r)
<type 'int'>
sage: type(0Xa1R)
<type 'int'>
The preparser can handle PEP 515 (see trac ticket #28490):
In Sage, methods can also be called on integer and real literals (note that in pure Python this would be a syntax error):
sage: 16.sqrt()
4
sage: 87.factor()
3 * 29
sage: 15.10.sqrt()
(continues on next page)
12 Chapter 2. Preparsing
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
Note that calling methods on int literals in pure Python is a syntax error, but Sage allows this for Sage integers and
reals, because users frequently request it:
sage: eval('4.__add__(3)')
Traceback (most recent call last):
...
SyntaxError: invalid syntax
This involves an =-, but should still be turned into a symbolic expression:
sage: preparse('a(x) =- 5')
'__tmp__=var("x"); a = symbolic_expression(- Integer(5)).function(x)'
sage: f(x)=-x
sage: f(10)
-10
This involves -=, which should not be turned into a symbolic expression (of course a(x) isn’t an identifier, so this will
never be valid):
sage: preparse('a(x) -= 5')
'a(x) -= Integer(5)'
Raw literals:
Raw literals are not preparsed, which can be useful from an efficiency point of view. Just like Python ints are denoted
by an L, in Sage raw integer and floating literals are followed by an”r” (or “R”) for raw, meaning not preparsed.
We create a raw integer:
sage: a = 393939r
sage: a
393939
sage: type(a)
<type 'int'>
sage: z = 1.5949r
sage: z
1.5949
sage: type(z)
<type 'float'>
sage: z = 3.1415R
sage: z
3.1415
sage: type(z)
<type 'float'>
This next example illustrates how raw literals can be very useful in certain cases. We make a list of even integers up
to 10000:
This takes a noticeable fraction of a second (e.g., 0.25 seconds). After preparsing, what Python is really executing is
the following:
Warning: The results of the above two expressions are different. The first one computes a list of Sage integers,
whereas the second creates a list of Python integers. Python integers are typically much more efficient than Sage
integers when they are very small; large Sage integers are much more efficient than Python integers, since they are
implemented using the GMP C library.
14 Chapter 2. Preparsing
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
• a 2-tuple (a,b) of integers, such that code[a:b] is delimited by balanced delimiters, a<=idx<b, and
a is maximal and b is minimal with that property. If that does not exist, a SyntaxError is raised.
• If require_delim is false and a,b as above can not be found, then 0, len(code) is returned.
EXAMPLES:
sage.repl.preparse.extract_numeric_literals(code)
Pulls out numeric literals and assigns them to global variables. This eliminates the need to re-parse and create
the literals, e.g., during every iteration of a loop.
INPUT:
• code - a string; a block of code
OUTPUT:
• a (string, string:string dictionary) 2-tuple; the block with literals replaced by variable names and a mapping
from names to the new variables
EXAMPLES:
sage.repl.preparse.handle_encoding_declaration(contents, out)
Find a PEP 263-style Python encoding declaration in the first or second line of contents. If found, output
it to out and return contents without the encoding line; otherwise output a default UTF-8 declaration and
return contents.
EXAMPLES:
Note:
• PEP 263 says that Python will interpret a UTF-8 byte order mark as a declaration of UTF-8 encoding, but
I don’t think we do that; this function only sees a Python string so it can’t account for a BOM.
• We default to UTF-8 encoding even though PEP 263 says that Python files should default to ASCII.
• Also see https://docs.python.org/ref/encodings.html.
AUTHORS:
• Lars Fischer
• Dan Drake (2010-12-08, rewrite for trac ticket #10440)
sage.repl.preparse.implicit_mul(code, level=5)
Insert *’s to make implicit multiplication explicit.
INPUT:
• code – a string; the code with missing *’s
• level – an integer (default: 5); see implicit_multiplication() for a list
OUTPUT:
• a string
EXAMPLES:
16 Chapter 2. Preparsing
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
sage.repl.preparse.implicit_multiplication(level=None)
Turn implicit multiplication on or off, optionally setting a specific level.
INPUT:
• level – a boolean or integer (default: 5); how aggressive to be in placing *’s
– 0 - Do nothing
– 1 - Numeric followed by alphanumeric
– 2 - Closing parentheses followed by alphanumeric
– 3 - Spaces between alphanumeric
– 10 - Adjacent parentheses (may mangle call statements)
OUTPUT:
The current level if no argument is given.
EXAMPLES:
sage: implicit_multiplication(True)
sage: implicit_multiplication()
5
sage: preparse('2x')
'Integer(2)*x'
sage: implicit_multiplication(False)
sage: preparse('2x')
'2x'
Note that the IPython automagic feature cannot be used if level >= 3:
sage: implicit_multiplication(3)
sage: preparse('cd Documents')
'cd*Documents'
sage: implicit_multiplication(2)
sage: preparse('cd Documents')
'cd Documents'
sage: implicit_multiplication(False)
In this case, one can use the explicit syntax for IPython magics such as %cd Documents.
sage.repl.preparse.in_quote()
sage.repl.preparse.isalphadigit_(s)
Return True if s is a non-empty string of alphabetic characters or a non-empty string of digits or just a single
_
EXAMPLES:
sage.repl.preparse.parse_ellipsis(code, preparse_step=True)
Preparses [0,2,..,n] notation.
INPUT:
• code - a string
• preparse_step - a boolean (default: True)
OUTPUT:
• a string
EXAMPLES:
sage: preparse("a^b")
'a**b'
sage: preparse("a^^b")
'a^b'
sage: 8^1
(continues on next page)
18 Chapter 2. Preparsing
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
˓→(x,) = R._first_ngens(1)'
sage.repl.preparse.preparse_calculus(code)
Supports calculus-like function assignment, e.g., transforms:
into:
__tmp__=var("x,y,z")
f = symbolic_expression(sin(x**3 - 4*y) + y**x).function(x,y,z)
AUTHORS:
• Bobby Moretti
– Initial version - 02/2007
• William Stein
– Make variables become defined if they aren’t already defined.
• Robert Bradshaw
– Rewrite using regular expressions (01/2009)
EXAMPLES:
For simplicity, this function assumes all statements begin and end with a semicolon:
Note: Temporarily, if @parallel is in the input, then numeric_literals is always set to False.
INPUT:
• contents - a string
• globals - dict or None (default: None); if given, then arguments to load/attach are evaluated in the
namespace of this dict.
• numeric_literals - bool (default: True), whether to factor out wrapping of integers and floats, so
they don’t get created repeatedly inside loops
OUTPUT:
• a string
sage.repl.preparse.preparse_file_named(name)
Preparse file named code{name} (presumably a .sage file), outputting to a temporary file. Returns name of
temporary file.
sage.repl.preparse.preparse_file_named_to_stream(name, out)
Preparse file named code{name} (presumably a .sage file), outputting to stream code{out}.
sage.repl.preparse.preparse_generators(code)
Parses generator syntax, converting:
obj.<gen0,gen1,...,genN> = objConstructor(...)
into:
obj = objConstructor(..., names=("gen0", "gen1", ..., "genN"))
(gen0, gen1, ..., genN,) = obj.gens()
and:
obj.<gen0,gen1,...,genN> = R[interior]
into:
obj = R[interior]; (gen0, gen1, ..., genN,) = obj.gens()
INPUT:
• code - a string
OUTPUT:
• a string
LIMITATIONS:
• The entire constructor must be on one line.
20 Chapter 2. Preparsing
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
AUTHORS:
• 2006-04-14: Joe Wetherell ([email protected])
– Initial version.
• 2006-04-17: William Stein
– Improvements to allow multiple statements.
• 2006-05-01: William
– Fix bug that Joe found.
• 2006-10-31: William
– Fix so obj doesn’t have to be mutated.
• 2009-01-27: Robert Bradshaw
– Rewrite using regular expressions
sage.repl.preparse.preparse_numeric_literals(code, extract=False)
This preparses numerical literals into their Sage counterparts, e.g. Integer, RealNumber, and ComplexNumber.
INPUT:
• code - a string; a code block to preparse
• extract - a boolean (default: False); whether to create names for the literals and return a dictionary of
name-construction pairs
OUTPUT:
• a string or (string, string:string dictionary) 2-tuple; the preparsed block and, if extract is True, the
name-construction mapping
EXAMPLES:
22 Chapter 2. Preparsing
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
Having consecutive underscores is not valid Python syntax, so it is not preparsed, and similarly with a trailing
underscore:
sage: preparse_numeric_literals('123__45')
'123__45'
sage: 123__45 # py2
Traceback (most recent call last):
...
SyntaxError: invalid syntax
sage: 123__45 # py3
Traceback (most recent call last):
...
SyntaxError: invalid token
sage: preparse_numeric_literals('3040_1_')
'3040_1_'
sage: 3040_1_ # py2
Traceback (most recent call last):
...
SyntaxError: invalid syntax
sage: 3040_1_ # py3
Traceback (most recent call last):
...
SyntaxError: invalid token
sage.repl.preparse.strip_prompts(line)
Removes leading sage: and >>> prompts so that pasting of examples from the documentation works.
INPUT:
• line - a string to process
OUTPUT:
• a string stripped of leading prompts
EXAMPLES:
sage.repl.preparse.strip_string_literals(code, state=None)
Returns a string with all literal quotes replaced with labels and a dictionary of labels for re-substitution. This
makes parsing easier.
INPUT:
• code - a string; the input
• state - a 2-tuple (default: None); state with which to continue processing, e.g., across multiple calls to
this function
OUTPUT:
• a 3-tuple of the processed code, the dictionary of labels, and any accumulated state
EXAMPLES:
A state is returned so one can break strings across multiple calls to this function:
24 Chapter 2. Preparsing
CHAPTER
THREE
Sage or Python files can be loaded (similar to Python’s execfile) in a Sage session. Attaching is similar, except
that the attached file is reloaded whenever it is changed.
3.1 Load Python, Sage, Cython, Fortran and Magma files in Sage
sage.repl.load.is_loadable_filename(filename)
Returns whether a file can be loaded into Sage. This checks only whether its name ends in one of the supported
extensions .py, .pyx, .sage, .spyx, .f, .f90 and .m. Note: load() assumes the latter signifies a
Magma file.
INPUT:
• filename - a string
OUTPUT:
• a boolean
EXAMPLES:
sage: sage.repl.load.is_loadable_filename('foo.bar')
False
sage: sage.repl.load.is_loadable_filename('foo.c')
False
sage: sage.repl.load.is_loadable_filename('foo.sage')
True
sage: sage.repl.load.is_loadable_filename('FOO.F90')
True
sage: sage.repl.load.is_loadable_filename('foo.m')
True
Note: For Cython files, the situation is more complicated – the module is first compiled to a temporary module
t and executed via:
from t import *
INPUT:
25
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
sage: t = tmp_filename(ext='.py')
sage: with open(t, 'w') as f:
....: _ = f.write("print(('hi', 2^3)); z = -2^7")
sage: z = 1
sage: sage.repl.load.load(t, globals())
('hi', 1)
sage: z
-7
sage: t = tmp_filename(ext='.sage')
sage: with open(t, 'w') as f:
....: _ = f.write("print(('hi', 2^3)); z = -2^7")
sage: z = 1
sage: sage.repl.load.load(t, globals())
('hi', 8)
sage: z
-128
sage: t = tmp_filename(ext='.pyx')
sage: with open(t, 'w') as f:
....: _ = f.write("print(('hi', 2^3)); z = -2^7")
sage: z = 1
sage: sage.repl.load.load(t, globals())
Compiling ...
('hi', 1)
sage: z
-7
We load a file given at a remote URL (not tested for security reasons):
sage: sage.repl.load.load('https://raw.githubusercontent.com/sagemath/sage-
˓→patchbot/3.0.0/sage_patchbot/util.py', globals()) # optional - internet
We attach a file:
sage: t = tmp_filename(ext='.py')
sage: with open(t, 'w') as f:
....: _ = f.write("print('hello world')")
sage: sage.repl.load.load(t, globals(), attach=True)
hello world
sage: t in attached_files()
True
The default search path for loading and attaching files is the current working directory, i.e., '.'. But you can
modify the path with load_attach_path():
$ export SAGE_LOAD_ATTACH_PATH="/path/to/my/library:/path/to/utils"
$ sage
sage: load_attach_path() # not tested
['.', '/path/to/my/library', '/path/to/utils']
sage.repl.load.load_cython(name)
Helper function to load a Cython file.
INPUT:
• name – filename of the Cython file
3.1. Load Python, Sage, Cython, Fortran and Magma files in Sage 27
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
OUTPUT:
• A string with Python code to import the names from the compiled module.
sage.repl.load.load_wrap(filename, attach=False)
Encodes a load or attach command as valid Python code.
INPUT:
• filename - a string; the argument to the load or attach command
• attach - a boolean (default: False); whether to attach filename, instead of loading it
OUTPUT:
• a string
EXAMPLES:
sage: sage.repl.load.load_wrap('foo.py', True)
'sage.repl.load.load(sage.repl.load.base64.b64decode("Zm9vLnB5"),globals(),True)'
sage: sage.repl.load.load_wrap('foo.sage')
'sage.repl.load.load(sage.repl.load.base64.b64decode("Zm9vLnNhZ2U="),globals(),
˓→False)'
sage: m = sage.repl.load.base64.b64decode("Zm9vLnNhZ2U=")
sage: m == b'foo.sage'
True
sage.repl.attach.add_attached_file(filename)
Add to the list of attached files
This is a callback to be used from load() after evaluating the attached file the first time.
INPUT:
• filename – string, the fully qualified file name.
EXAMPLES:
sage: import sage.repl.attach as af
sage: af.reset()
sage: t = tmp_filename(ext='.py')
sage: af.add_attached_file(t)
sage: af.attached_files()
['/.../tmp_....py']
sage: af.detach(t)
sage: af.attached_files()
[]
sage.repl.attach.attach(*files)
Attach a file or files to a running instance of Sage and also load that file.
Note: Attaching files uses the Python inputhook, which will conflict with other inputhook users. This generally
includes GUI main loop integrations, for example tkinter. So you can only use tkinter or attach, but not both at
the same time.
INPUT:
sage: sage.repl.attach.reset()
sage: t1 = tmp_filename(ext='.py')
sage: with open(t1,'w') as f: _ = f.write("print('hello world')")
sage: t2 = tmp_filename(ext='.py')
sage: with open(t2,'w') as f: _ = f.write("print('hi there xxx')")
sage: attach(t1, t2)
hello world
hi there xxx
sage: set(attached_files()) == set([t1,t2])
True
See also:
sage.repl.attach.attached_files()
Returns a list of all files attached to the current session with attach().
OUTPUT:
The filenames in a sorted list of strings.
EXAMPLES:
sage: sage.repl.attach.reset()
sage: t = tmp_filename(ext='.py')
sage: with open(t,'w') as f: _ = f.write("print('hello world')")
sage: attach(t)
hello world
sage: attached_files()
['/....py']
sage: attached_files() == [t]
True
sage.repl.attach.detach(filename)
Detach a file.
This is the counterpart to attach().
INPUT:
• filename – a string, or a list of strings, or a tuple of strings.
EXAMPLES:
sage: sage.repl.attach.reset()
sage: t = tmp_filename(ext='.py')
sage: with open(t,'w') as f: _ = f.write("print('hello world')")
sage: attach(t)
hello world
sage: attached_files() == [t]
True
sage: detach(t)
sage: attached_files()
[]
sage.repl.attach.load_attach_mode(load_debug=None, attach_debug=None)
Get or modify the current debug mode for the behavior of load() and attach() on .sage files.
In debug mode, loaded or attached .sage files are preparsed through a file to make their tracebacks more
informative. If not in debug mode, then .sage files are preparsed in memory only for performance.
At startup, debug mode is True for attaching and False for loading.
Note: This function should really be deprecated and code executed from memory should raise proper trace-
backs.
INPUT:
• load_debug – boolean or None (default); if not None, then set a new value for the debug mode for
loading files.
• attach_debug – boolean or None (default); same as load_debug, but for attaching files.
OUTPUT:
If all input values are None, returns a tuple giving the current modes for loading and attaching.
EXAMPLES:
sage: load_attach_mode()
(False, True)
sage: load_attach_mode(attach_debug=False)
sage: load_attach_mode()
(False, False)
sage: load_attach_mode(load_debug=True)
sage: load_attach_mode()
(True, False)
sage: load_attach_mode(load_debug=False, attach_debug=True)
sage.repl.attach.load_attach_path(path=None, replace=False)
Get or modify the current search path for load() and attach().
INPUT:
• path – string or list of strings (default: None); path(s) to append to or replace the current path.
• replace – boolean (default: False); if path is not None, whether to replace the search path instead
of appending to it.
OUTPUT:
None or a reference to the current search paths.
EXAMPLES:
First, we extend the example given in load()’s docstring:
We put SAGE_TMP on the attach path for testing (otherwise this will load test.py from the current working
directory if that happens to exist):
sage.repl.attach.modified_file_iterator()
Iterate over the changed files
As a side effect the stored time stamps are updated with the actual time stamps. So if you iterate over the
attached files in order to reload them and you hit an error then the subsequent files are not marked as read.
Files that are in the process of being saved are excluded.
EXAMPLES:
sage: sage.repl.attach.reset()
sage: t = tmp_filename(ext='.py')
sage: attach(t)
sage: from sage.repl.attach import modified_file_iterator
sage: list(modified_file_iterator())
[]
sage: sleep(1) # filesystem mtime granularity
sage: with open(t, 'w') as f: _ = f.write('1')
sage: list(modified_file_iterator())
[('/.../tmp_....py', time.struct_time(...))]
sage.repl.attach.reload_attached_files_if_modified()
Reload attached files that have been modified
sage: sage.repl.attach.reset()
sage: from sage.repl.interpreter import get_test_shell
sage: shell = get_test_shell()
sage: tmp = tmp_filename(ext='.py')
sage: with open(tmp, 'w') as f: _ = f.write('a = 2\n')
sage: shell.run_cell('attach({0})'.format(repr(tmp)))
sage: shell.run_cell('a')
2
sage: sleep(1) # filesystem mtime granularity
sage: with open(tmp, 'w') as f: _ = f.write('a = 3\n')
Note that the doctests are never really at the command prompt where the automatic reload is triggered. So we
have to do it manually:
sage: shell.run_cell('reload_attached_files_if_modified()')
### reloading attached file tmp_....py modified at ... ###
sage: shell.run_cell('a')
3
sage: shell.run_cell('detach({0})'.format(repr(tmp)))
sage: shell.run_cell('attached_files()')
[]
sage: shell.quit()
sage.repl.attach.reset()
Remove all the attached files from the list of attached files.
EXAMPLES:
sage: sage.repl.attach.reset()
sage: t = tmp_filename(ext='.py')
sage: with open(t,'w') as f: _ = f.write("print('hello world')")
sage: attach(t)
hello world
sage: attached_files() == [t]
True
sage: sage.repl.attach.reset()
sage: attached_files()
[]
sage.repl.attach.reset_load_attach_path()
Resets the current search path for load() and attach().
The default path is '.' plus any paths specified in the environment variable SAGE_LOAD_ATTACH_PATH.
EXAMPLES:
sage: load_attach_path()
['.']
sage: t_dir = tmp_dir()
sage: load_attach_path(t_dir)
sage: t_dir in load_attach_path()
True
(continues on next page)
FOUR
PRETTY PRINTING
In addition to making input nicer, we also modify how results are printed. This again builds on how IPython formats
output. Technically, this works using a modified displayhook in Python.
The classes in this module can be used as IPython displayhook formatters. It has two main features, by default the
displayhook contains a new facility for displaying lists of matrices in an easier to read format:
sage: [identity_matrix(i) for i in range(2,5)]
[
[1 0 0 0]
[1 0 0] [0 1 0 0]
[1 0] [0 1 0] [0 0 1 0]
[0 1], [0 0 1], [0 0 0 1]
]
This facility uses _repr_() (and a simple string) to try do a nice read format (see sage.structure.parent.
Parent._repr_option() for details).
With this displayhook there exists an other way for displaying object and more generally, all sage expression as an
ASCII art object:
sage: from sage.repl.interpreter import get_test_shell
sage: shell = get_test_shell()
sage: shell.run_cell('%display ascii_art')
sage: shell.run_cell('integral(x^2/pi^x, x)')
-x / 2 2 \
-pi *\x *log (pi) + 2*x*log(pi) + 2/
--------------------------------------
3
log (pi)
sage: shell.run_cell("i = var('i')")
sage: shell.run_cell('sum(i*x^i, i, 0, 10)')
10 9 8 7 6 5 4 3 2
10*x + 9*x + 8*x + 7*x + 6*x + 5*x + 4*x + 3*x + 2*x + x
sage: shell.run_cell('StandardTableaux(4).list()')
[
[ 1 4 1 3
[ 1 3 4 1 2 4 1 2 3 1 3 1 2 2 2
[ 1 2 3 4, 2 , 3 , 4 , 2 4, 3 4, 3 , 4 ,
1 ]
(continues on next page)
35
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
This other facility uses a simple AsciiArt object (see and sage.structure.sage_object.SageObject.
_ascii_art_()).
class sage.repl.display.formatter.SageDisplayFormatter(*args, **kwds)
Bases: IPython.core.formatters.DisplayFormatter
This is where the Sage rich objects are translated to IPython
INPUT/OUTPUT:
See the IPython documentation.
EXAMPLES:
This is part of how Sage works with the IPython output system. It cannot be used in doctests:
default_mime()
Return the default mime output(s)
If these are the only output mime types from the Sage rich output machinery, then format() will try to
fall back to IPythons internal formatting.
OUTPUT:
List of mime type strings. Usually just text/plain, though possibly more depending on display manager
preferences.
EXAMPLES:
EXAMPLES:
Warning: This IPython formatter is NOT used. You could use it to enable Sage formatting in IPython, but
Sage uses its own rich output system that is more flexible and supports different backends.
INPUT/OUTPUT:
See the IPython documentation.
EXAMPLES:
Any transformation to a string goes through here. In other words, the SagePlainTextFormatter is entirely im-
plemented via SagePrettyPrinter. Other formatters may or may not use SagePrettyPrinter to generate
text output.
AUTHORS:
• Bill Cauchois (2009): initial version
• Jean-Baptiste Priez <[email protected]> (2013): ASCII art
• Volker Braun (2013): refactored into DisplayHookBase
sage: 123
123
These are overridden in IPython in a way that we feel is somewhat confusing, and we prefer to print them like
plain Python which is more informative. See trac ticket #14466
pretty(obj)
Pretty print obj
This is the only method that outside code should invoke.
INPUT:
• obj – anything.
OUTPUT:
String representation for object.
EXAMPLES:
toplevel()
Return whether we are currently at the top level.
OUTPUT:
Boolean. Whether we are currently pretty-printing an object at the outermost level (True), or whether the
object is inside a container (False).
EXAMPLES:
class sage.repl.display.fancy_repr.LargeMatrixHelpRepr
Bases: sage.repl.display.fancy_repr.ObjectReprABC
Representation including help for large Sage matrices
__call__(obj, p, cycle)
Format matrix.
INPUT:
• obj – anything. Object to format.
• p – PrettyPrinter instance.
• cycle – boolean. Whether there is a cycle.
OUTPUT:
Boolean. Whether the representer is applicable to obj. If True, the string representation is appended to
p.
EXAMPLES:
Leads to:
sage: M
40 x 40 dense matrix over Integer Ring (use the '.str()' method to see the
˓→entries)
sage: [M, M]
[40 x 40 dense matrix over Integer Ring,
40 x 40 dense matrix over Integer Ring]
class sage.repl.display.fancy_repr.ObjectReprABC
Bases: object
The abstract base class of an object representer.
__call__(obj, p, cycle)
Format object.
INPUT:
• obj – anything. Object to format.
• p – PrettyPrinter instance.
• cycle – boolean. Whether there is a cycle.
OUTPUT:
Boolean. Whether the representer is applicable to obj. If True, the string representation is appended to
p.
EXAMPLES:
format_string(obj)
For doctesting only: Directly return string.
INPUT:
• obj – anything. Object to format.
OUTPUT:
String.
EXAMPLES:
class sage.repl.display.fancy_repr.PlainPythonRepr
Bases: sage.repl.display.fancy_repr.ObjectReprABC
The ordinary Python representation
__call__(obj, p, cycle)
Format matrix.
INPUT:
• obj – anything. Object to format.
• p – PrettyPrinter instance.
• cycle – boolean. Whether there is a cycle.
OUTPUT:
Boolean. Whether the representer is applicable to obj. If True, the string representation is appended to
p.
EXAMPLES:
Do not swallow a trailing newline at the end of the output of a custom representer. Note that it is undesirable
to have a trailing newline, and if we don’t display it you can’t fix it:
class sage.repl.display.fancy_repr.SomeIPythonRepr
Bases: sage.repl.display.fancy_repr.ObjectReprABC
Some selected representers from IPython
EXAMPLES:
__call__(obj, p, cycle)
Format object.
INPUT:
• obj – anything. Object to format.
• p – PrettyPrinter instance.
• cycle – boolean. Whether there is a cycle.
OUTPUT:
Boolean. Whether the representer is applicable to obj. If True, the string representation is appended to
p.
EXAMPLES:
class sage.repl.display.fancy_repr.TallListRepr
Bases: sage.repl.display.fancy_repr.ObjectReprABC
Special representation for lists with tall entries (e.g. matrices)
__call__(obj, p, cycle)
Format list/tuple.
INPUT:
• obj – anything. Object to format.
• p – PrettyPrinter instance.
• cycle – boolean. Whether there is a cycle.
OUTPUT:
Boolean. Whether the representer is applicable to obj. If True, the string representation is appended to
p.
EXAMPLES:
These utility functions are used in the implementations of _repr_ methods elsewhere.
class sage.repl.display.util.TallListFormatter
Bases: object
Special representation for lists with tall entries (e.g. matrices)
__call__(the_list)
Return “tall list” string representation.
See also try_format().
INPUT:
try_format(the_list)
First check whether a list is “tall” – whether the reprs of the elements of the list will span multiple lines
and cause the list to be printed awkwardly. If not, this function returns None and does nothing; you
should revert back to the normal method for printing an object (its repr). If so, return the string in the
special format. Note that the special format isn’t just for matrices. Any object with a multiline repr will be
formatted.
INPUT:
• the_list - The list (or a tuple).
OUTPUT:
String or None. The latter is returned if the list is not deemed to be tall enough and another formatter
should be used.
FIVE
This is the heart of the rich output system, the display manager arbitrates between
• Backend capabilities: what can be displayed
• Backend preferences: what gives good quality on the backend
• Sage capabilities: every Sage object can only generate certain representations, and
• User preferences: typeset vs. plain text vs. ascii art, etc.
The display manager is a singleton class, Sage always has exactly one instance of it. Use
get_display_manager() to obtain it.
EXAMPLES:
exception sage.repl.rich_output.display_manager.DisplayException
Bases: Exception
Base exception for all rich output-related exceptions.
EXAMPLES:
class sage.repl.rich_output.display_manager.DisplayManager
Bases: sage.structure.sage_object.SageObject
The Display Manager
Used to decide what kind of rich output is best.
EXAMPLES:
45
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
check_backend_class(backend_class)
Check that the current backend is an instance of backend_class.
This is, for example, used by the Sage IPython display formatter to ensure that the IPython backend is in
use.
INPUT:
• backend_class – type of a backend class.
OUTPUT:
This method returns nothing. A RuntimeError is raised if backend_class is not the type of the
current backend.
EXAMPLES:
display_immediately(obj, **rich_repr_kwds)
Show output without going back to the command line prompt.
This method must be called to create rich output from an object when we are not returning to the com-
mand line prompt, for example during program execution. Typically, it is being called by sage.plot.
graphics.Graphics.show().
INPUT:
• obj – anything. The object to be shown.
• rich_repr_kwds – optional keyword arguments that are passed through to obj._rich_repr_.
EXAMPLES:
displayhook(obj)
Implementation of the displayhook
Every backend must pass the value of the last statement of a line / cell to this method. See also
display_immediately() if you want do display rich output while a program is running.
INPUT:
• obj – anything. The object to be shown.
OUTPUT:
Returns whatever the backend’s displayhook method returned.
EXAMPLES:
classmethod get_instance()
Get the singleton instance.
This class method is equivalent to get_display_manager().
OUTPUT:
The display manager singleton.
EXAMPLES:
sage: out
OutputImagePng container
sage: out.png.get().startswith(b'\x89PNG')
True
sage: out.png.filename() # random
'/home/user/.sage/temp/localhost.localdomain/23903/tmp_pu5woK.png'
is_in_terminal()
Test whether the UI is meant to run in a terminal
When this method returns True, you can assume that it is possible to use raw_input or launch external
programs that take over the input.
Otherwise, you should assume that the backend runs remotely or in a pty controlled by another program.
Then you should not launch external programs with a (text or graphical) UI.
This is used to enable/disable interpreter consoles.
OUTPUT:
Boolean.
preferences
Return the preferences.
OUTPUT:
The display preferences as instance of DisplayPreferences.
EXAMPLES:
supported_output()
Return the output container classes that can be used.
OUTPUT:
Frozen set of subclasses of OutputBase. If the backend defines derived container classes, this method
will always return their base classes.
EXAMPLES:
switch_backend(backend, **kwds)
Switch to a new backend
INPUT:
• backend – instance of BackendBase.
• kwds – optional keyword arguments that are passed on to the install() method.
OUTPUT:
The previous backend.
EXAMPLES:
threejs_scripts(online)
Return Three.js script tags for the current backend.
INPUT:
• online – Boolean determining script usage context
OUTPUT:
String containing script tags
Note: This base method handles online=True case only, serving CDN script tags. Location of scripts
for offline usage is backend-specific.
EXAMPLES:
types
Catalog of all output container types.
Note that every output type must be registered in sage.repl.rich_output.output_catalog.
OUTPUT:
Returns the sage.repl.rich_output.output_catalog module.
EXAMPLES:
exception sage.repl.rich_output.display_manager.OutputTypeException
Bases: sage.repl.rich_output.display_manager.DisplayException
exception sage.repl.rich_output.display_manager.RichReprWarning
Bases: UserWarning
Warning that is throws if a call to _rich_repr_ fails.
If an object implements _rich_repr_ then it must return a value, possibly None to indicate that no rich
output can be generated. But it may not raise an exception as it is very confusing for the user if the displayhook
fails.
EXAMPLES:
class sage.repl.rich_output.display_manager.restricted_output(display_manager,
output_classes)
Bases: object
Context manager to temporarily restrict the accepted output types
In the context, the output is restricted to the output container types listed in output_classes. Additionally,
display preferences are changed not to show graphics.
INPUT:
• display_manager – the display manager.
• output_classes – iterable of output container types.
EXAMPLES:
This class is used to express display preferences that are not simply a choice of a particular output format. For example,
whether to prefer vector over raster graphics. By convention, the value None is always a valid value for a preference
and means no particular preference.
EXAMPLES:
sage: from sage.repl.rich_output.preferences import DisplayPreferences
sage: prefs = DisplayPreferences()
sage: prefs.available_options()
(graphics, supplemental_plot, text)
sage: prefs.text is None
True
sage: prefs.text = 'ascii_art'
sage: prefs.text
'ascii_art'
sage: prefs
Display preferences:
* graphics is not specified
* supplemental_plot is not specified
* text = ascii_art
Todo: A value-checking preference system should be used elsewhere in Sage, too. The class here is just a simple
implementation, a proper implementation would use a metaclass to construct the preference items.
• ‘disable’
• ‘vector’
• ‘raster’
supplemental_plot
Whether to graphically display graphs and other graph-like objects that implement rich output. When not
specified small objects are show graphically and large objects as textual overview.
Allowed values:
• None (default): no preference
• ‘always’
• ‘never’
text
Which textual representation is preferred
Allowed values:
• None (default): no preference
• ‘plain’
• ‘ascii_art’
• ‘unicode_art’
• ‘latex’
class sage.repl.rich_output.preferences.PreferencesABC(*args, **kwds)
Bases: sage.structure.sage_object.SageObject
Preferences for displaying graphics
These can be preferences expressed by the user or by the display backend. They are specified as keyword
arguments.
INPUT:
• *args* – positional arguments are preferences instances. The property values will be inherited from left
to right, that is, later parents override values from earlier parents.
• **kwds – keyword arguments. Will be used to initialize properties, and override inherited values if
necessary.
EXAMPLES:
available_options()
Return the available options
OUTPUT:
Tuple of the preference items as instances of Property.
EXAMPLES:
sage: prop.allowed_values
(0, 1, 2)
deleter(prefs)
Delete the current value of the property
INPUT:
• prefs – the PreferencesABC instance that the property is bound to.
EXAMPLES:
getter(prefs)
Get the current value of the property
INPUT:
• prefs – the PreferencesABC instance that the property is bound to.
OUTPUT:
One of the allowed values or None if not set.
EXAMPLES:
setter(prefs, value)
Get the current value of the property
INPUT:
• prefs – the PreferencesABC instance that the property is bound to.
• value – anything. The new value of the property. Setting a property to None is equivalent to deleting
the value.
OUTPUT:
This method does not return anything. A ValueError is raised if the given value is not one of the
allowed values.
EXAMPLES:
This is the fundamental unit of rich output, a single immutable buffer (either in-memory or as a file). Rich output
always consists of one or more buffers. Ideally, the Sage library always uses the buffer object as an in-memory buffer.
But you can also ask it for a filename, and it will save the data to a file if necessary. Either way, the buffer object
presents the same interface for getting the content of an in-memory buffer or a temporary file. So any rich output
backends do not need to know where the buffer content is actually stored.
EXAMPLES:
class sage.repl.rich_output.buffer.OutputBuffer(data)
Bases: sage.structure.sage_object.SageObject
Data stored either in memory or as a file
This class is an abstraction for “files”, in that they can either be defined by a bytes array (Python 3) or string
(Python 2) or by a file (see from_file()).
INPUT:
• data – bytes. The data that is stored in the buffer.
EXAMPLES:
sage: buf.get_str()
'this is the buffer content'
sage: buf.filename(ext='.txt')
'/....txt'
filename(ext=None)
Return the filename.
INPUT:
• ext – string. The file extension.
OUTPUT:
Name of a file, most likely a temporary file. If ext is specified, the filename will have that extension.
You must not modify the returned file. Its permissions are set to readonly to help with that.
EXAMPLES:
sage: os.path.isfile(buf.filename())
True
sage: buf.filename(ext='txt') # random output
'/home/user/.sage/temp/hostname/26085/tmp_Rjjp4V.txt'
sage: buf.filename(ext='txt').endswith('.txt')
True
classmethod from_file(filename)
Construct buffer from data in file.
Warning: The buffer assumes that the file content remains the same during the lifetime of the Sage
session. To communicate this to the user, the file permissions will be changed to read only.
INPUT:
• filename – string. The filename under which the data is stored.
OUTPUT:
String containing the buffer data.
EXAMPLES:
get()
Return the buffer content
OUTPUT:
Bytes. A string in Python 2.x.
EXAMPLES:
get_str()
Return the buffer content as a str object for the current Python version.
That is, returns a Python 2-style encoding-agnostic str on Python 2, and returns a unicode str on Python
3 with the buffer content decoded from UTF-8. In other words, this is equivalent to OutputBuffer.
get on Python 2 and OutputBuffer.get_unicode on Python 3. This is useful in some cases for
cross-compatible code.
OUTPUT:
A str object.
EXAMPLES:
get_unicode()
Return the buffer content as string
OUTPUT:
String. Unicode in Python 2.x. Raises a UnicodeEncodeError if the data is not valid utf-8.
EXAMPLES:
save_as(filename)
Save a copy of the buffer content.
You may edit the returned file, unlike the file returned by filename().
INPUT:
• filename – string. The file name to save under.
EXAMPLES:
The Sage rich representation system requires a special container class to hold the data for each type of rich output.
They all inherit from OutputBase, though a more typical example is OutputPlainText. Some output classes
consist of more than one data buffer, for example jmol or certain animation formats. The output class is independent
of user preferences and of the display backend.
The display backends can define derived classes to attach backend-specific display functionality to, for example
how to launch a viewer. But they must not change how the output container is created. To enforce this, the Sage
_rich_repr_ magic method will only ever see the output class defined here. The display manager will promote it
to a backend-specific subclass if necessary prior to displaying it.
To create new types of output, you must create your own subclass of OutputBase and register it in sage.repl.
rich_output.output_catalog.
Warning: All rich output data in subclasses of OutputBase must be contained in OutputBuffer instances.
You must never reference any files on the local file system, as there is no guarantee that the notebook server and
the worker process are on the same computer. Or even share a common file system.
class sage.repl.rich_output.output_basic.OutputAsciiArt(ascii_art)
Bases: sage.repl.rich_output.output_basic.OutputBase
ASCII Art Output
INPUT:
• ascii_art – OutputBuffer. Alternatively, a string (bytes) can be passed directly which will then be
converted into an OutputBuffer. Ascii art rendered into a string.
EXAMPLES:
classmethod example()
Construct a sample ascii art output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputAsciiArt.
EXAMPLES:
print_to_stdout()
Write the data to stdout.
This is just a convenience method to help with debugging.
EXAMPLES:
class sage.repl.rich_output.output_basic.OutputBase
Bases: sage.structure.sage_object.SageObject
Base class for all rich output containers.
classmethod example()
Construct a sample instance
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of the OutputBase subclass.
EXAMPLES:
sage: from sage.repl.rich_output.output_basic import OutputBase
sage: OutputBase.example()
Traceback (most recent call last):
...
NotImplementedError: derived classes must implement this class method
class sage.repl.rich_output.output_basic.OutputLatex(latex)
Bases: sage.repl.rich_output.output_basic.OutputBase
LaTeX Output
Note: The LaTeX commands will only use a subset of LaTeX that can be displayed by MathJax.
INPUT:
• latex – OutputBuffer. Alternatively, a string (bytes) can be passed directly which will then be
converted into an OutputBuffer. String containing the latex equation code. Excludes the surrounding
dollar signs / LaTeX equation environment. Also excludes the surrounding MathJax <html> tag.
EXAMPLES:
sage: from sage.repl.rich_output.output_catalog import OutputLatex
sage: OutputLatex('<html><script type="math/tex; mode=display">1</script></html>')
OutputLatex container
display_equation()
Return the LaTeX code for a display equation
OUTPUT:
String.
EXAMPLES:
sage: from sage.repl.rich_output.output_catalog import OutputLatex
sage: rich_output = OutputLatex('1')
sage: rich_output.latex
(continues on next page)
classmethod example()
Construct a sample LaTeX output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputLatex.
EXAMPLES:
inline_equation()
Return the LaTeX code for an inline equation
OUTPUT:
String.
EXAMPLES:
mathjax(display=True)
Return the LaTeX with a surrounding MathJax HTML code.
INPUT:
• display – boolean. Whether to return display (as opposed to inline) TeX.
EXAMPLES:
print_to_stdout()
Write the data to stdout.
This is just a convenience method to help with debugging.
EXAMPLES:
sage: from sage.repl.rich_output.output_catalog import OutputLatex
sage: rich_output = OutputLatex.example()
sage: rich_output.print_to_stdout()
\newcommand{\Bold}[1]{\mathbf{#1}}\int \sin\left(x\right)\,{d x}
class sage.repl.rich_output.output_basic.OutputPlainText(plain_text)
Bases: sage.repl.rich_output.output_basic.OutputBase
Plain Text Output
INPUT:
• plain_text – OutputBuffer. Alternatively, a bytes (string in Python 2.x) or string (unicode in
Python 2.x) can be passed directly which will then be converted into an OutputBuffer. The plain text
output.
This should always be exactly the same as the (non-rich) output from the _repr_ method. Every backend
object must support plain text output as fallback.
EXAMPLES:
sage: from sage.repl.rich_output.output_catalog import OutputPlainText
sage: OutputPlainText('foo')
OutputPlainText container
classmethod example()
Construct a sample plain text output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputPlainText.
EXAMPLES:
sage: from sage.repl.rich_output.output_catalog import OutputPlainText
sage: OutputPlainText.example()
OutputPlainText container
sage: OutputPlainText.example().text.get_str()
'Example plain text output'
print_to_stdout()
Write the data to stdout.
This is just a convenience method to help with debugging.
EXAMPLES:
sage: from sage.repl.rich_output.output_catalog import OutputPlainText
sage: plain_text = OutputPlainText.example()
sage: plain_text.print_to_stdout()
Example plain text output
class sage.repl.rich_output.output_basic.OutputUnicodeArt(unicode_art)
Bases: sage.repl.rich_output.output_basic.OutputBase
classmethod example()
Construct a sample unicode art output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputUnicodeArt.
EXAMPLES:
print_to_stdout()
Write the data to stdout.
This is just a convenience method to help with debugging.
EXAMPLES:
This module defines the rich output types for 2-d images, both vector and raster graphics.
class sage.repl.rich_output.output_graphics.OutputImageDvi(dvi)
Bases: sage.repl.rich_output.output_basic.OutputBase
DVI Image
INPUT:
• dvi – OutputBuffer. Alternatively, a string (bytes) can be passed directly which will then be con-
verted into an OutputBuffer. The DVI data.
EXAMPLES:
classmethod example()
Construct a sample DVI output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputImageDvi.
EXAMPLES:
class sage.repl.rich_output.output_graphics.OutputImageGif(gif )
Bases: sage.repl.rich_output.output_basic.OutputBase
GIF Image (possibly animated)
INPUT:
• gif – OutputBuffer. Alternatively, a string (bytes) can be passed directly which will then be con-
verted into an OutputBuffer. The GIF image data.
EXAMPLES:
classmethod example()
Construct a sample GIF output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputImageGif.
EXAMPLES:
html_fragment()
Return a self-contained HTML fragment displaying the image
This is a workaround for the Jupyter notebook which doesn’t support GIF directly.
OUTPUT:
String. HTML fragment for displaying the GIF image.
EXAMPLES:
class sage.repl.rich_output.output_graphics.OutputImageJpg(jpg)
Bases: sage.repl.rich_output.output_basic.OutputBase
JPEG Image
INPUT:
• jpg – OutputBuffer. Alternatively, a string (bytes) can be passed directly which will then be con-
verted into an OutputBuffer. The JPEG image data.
EXAMPLES:
classmethod example()
Construct a sample JPEG output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputImageJpg.
EXAMPLES:
True
class sage.repl.rich_output.output_graphics.OutputImagePdf(pdf )
Bases: sage.repl.rich_output.output_basic.OutputBase
PDF Image
INPUT:
• pdf – OutputBuffer. Alternatively, a string (bytes) can be passed directly which will then be con-
verted into an OutputBuffer. The PDF data.
EXAMPLES:
classmethod example()
Construct a sample PDF output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputImagePdf.
EXAMPLES:
class sage.repl.rich_output.output_graphics.OutputImagePng(png)
Bases: sage.repl.rich_output.output_basic.OutputBase
PNG Image
Note: Every backend that is capable of displaying any kind of graphics is supposed to support the PNG format
at least.
INPUT:
• png – OutputBuffer. Alternatively, a string (bytes) can be passed directly which will then be con-
verted into an OutputBuffer. The PNG image data.
EXAMPLES:
classmethod example()
Construct a sample PNG output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputImagePng.
EXAMPLES:
class sage.repl.rich_output.output_graphics.OutputImageSvg(svg)
Bases: sage.repl.rich_output.output_basic.OutputBase
SVG Image
INPUT:
• svg – OutputBuffer. Alternatively, a string (bytes) can be passed directly which will then be con-
verted into an OutputBuffer. The SVG image data.
EXAMPLES:
classmethod example()
Construct a sample SVG output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputImageSvg.
EXAMPLES:
This module defines the rich output types for 3-d scenes.
class sage.repl.rich_output.output_graphics3d.OutputSceneCanvas3d(canvas3d)
Bases: sage.repl.rich_output.output_basic.OutputBase
Canvas3d Scene
INPUT:
• canvas3d – string/bytes. The canvas3d data.
EXAMPLES:
classmethod example()
Construct a sample Canvas3D output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputSceneCanvas3d.
EXAMPLES:
sage: rich_output.canvas3d
buffer containing 829 bytes
sage: rich_output.canvas3d.get_str()
'[{"vertices":[{"x":1,"y":1,"z":1},...{"x":1,"y":-1,"z":-1}],"faces":[[0,1,2,
˓→3]],"color":"008000"}]'
classmethod example()
Construct a sample Jmol output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputSceneJmol.
EXAMPLES:
sage: rich_output.scene_zip
buffer containing 654 bytes
sage: rich_output.scene_zip.get().startswith(b'PK')
True
sage: rich_output.preview_png
buffer containing 608 bytes
sage: rich_output.preview_png.get().startswith(b'\x89PNG')
True
launch_script_filename()
Return a launch script suitable to display the scene.
This method saves the scene to disk and creates a launch script. The latter contains an absolute path to the
scene file. The launch script is often necessary to make jmol render the 3d scene.
OUTPUT:
String. The file name of a suitable launch script.
EXAMPLES:
class sage.repl.rich_output.output_graphics3d.OutputSceneThreejs(html)
Bases: sage.repl.rich_output.output_basic.OutputBase
Three.js Scene
INPUT:
• html – string/bytes. The Three.js HTML data.
EXAMPLES:
classmethod example()
Construct a sample Canvas3D output container
This static method is meant for doctests, so they can easily construct an example.
OUTPUT:
An instance of OutputSceneCanvas3d.
EXAMPLES:
sage: rich_output.obj
buffer containing 227 bytes
sage: rich_output.obj.get_str()
'mtllib scene.mtl\ng obj_1\n...\nf 1 5 6 2\nf 1 4 7 5\nf 6 5 7 8\nf 7 4 3
˓→8\nf 3 2 6 8\n'
sage: rich_output.mtl
buffer containing 80 bytes
sage: rich_output.mtl.get_str()
'newmtl texture177\nKa 0.2 0.2 0.5\nKd 0.4 0.4 1.0\nKs 0.0 0.0 0.0\nillum
˓→1\nNs 1\nd 1\n'
mtllib()
Return the mtllib filename
The mtllib line in the Wavefront file format (*.obj) is the name of the separate texture file.
OUTPUT:
String. The filename under which mtl is supposed to be saved.
EXAMPLES:
obj_filename()
Return the file name of the .obj file
This method saves the object and texture to separate files in a temporary directory and returns the object
file name. This is often used to launch a 3d viewer.
OUTPUT:
String. The file name (absolute path) of the saved obj file.
EXAMPLES:
This module defines the rich output types for video formats.
class sage.repl.rich_output.output_video.OutputVideoAvi(video, loop=True)
Bases: sage.repl.rich_output.output_video.OutputVideoBase
AVI video
EXAMPLES:
sage: from sage.repl.rich_output.output_catalog import OutputVideoAvi
sage: OutputVideoAvi.example()
OutputVideoAvi container
classmethod example()
Construct a sample video output container
This static method is meant for doctests, so they can easily construct an example. The method is im-
plemented in the abstract OutputVideoBase class, but should get invoked on a concrete subclass for
which an actual example can exist.
OUTPUT:
An instance of the class on which this method is called.
EXAMPLES:
sage: from sage.repl.rich_output.output_catalog import OutputVideoOgg
sage: OutputVideoOgg.example()
OutputVideoOgg container
(continues on next page)
html_fragment(url, link_attrs=”)
Construct a HTML fragment for embedding this video
INPUT:
• url – string. The URL where the data of this video can be found.
• link_attrs – string. Can be used to style the fallback link which is presented to the user if the
video is not supported.
EXAMPLES:
class sage.repl.rich_output.output_video.OutputVideoQuicktime(video,
loop=True)
Bases: sage.repl.rich_output.output_video.OutputVideoBase
Quicktime video
EXAMPLES:
If you define another output type then you must add it to the imports here.
The display backends are the commandline, the SageNB notebook, the IPython notebook, the Emacs sage mode, the
Sage doctester, . . . . All of these have different capabilities for what they can display.
To implement a new display backend, you need to subclass BackendBase. All backend-specific handling of rich
output should be in displayhook() and display_immediately(). See BackendSimple for an absolutely
minimal example of a functioning backend.
You declare the types of rich output that your backend can handle in supported_output(). There are two ways
to then display specific output types in your own backend.
• Directly use one of the existing output containers listed in sage.repl.rich_output.
output_catalog. That is, test for the rich output type in display_immediately() and handle
it.
• Subclass the rich output container to attach your backend-specific functionality. Then
display_immediately() will receive instances of your subclass. See BackendTest for an ex-
ample of how this is done.
You can also mix both ways of implementing different rich output types.
EXAMPLES:
sage: from sage.repl.rich_output.backend_base import BackendSimple
sage: backend = BackendSimple()
sage: plain_text = backend.plain_text_formatter(list(range(10))); plain_text
OutputPlainText container
sage: backend.displayhook(plain_text, plain_text)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
class sage.repl.rich_output.backend_base.BackendBase
Bases: sage.structure.sage_object.SageObject
ascii_art_formatter(obj, **kwds)
Hook to override how ascii art is being formatted.
INPUT:
• obj – anything.
• **kwds – optional keyword arguments to control the formatting. Supported are:
– concatenate – boolean (default: False). If True, the argument obj must be iterable and
its entries will be concatenated. There is a single whitespace between entries.
OUTPUT:
Instance of OutputAsciiArt containing the ascii art string representation of the object.
EXAMPLES:
sage: from sage.repl.rich_output.backend_base import BackendBase
sage: backend = BackendBase()
sage: out = backend.ascii_art_formatter(list(range(30)))
sage: out
OutputAsciiArt container
sage: out.ascii_art
buffer containing 114 bytes
sage: print(out.ascii_art.get_str())
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
˓→21,
(continues on next page)
'[ 1, 2, 3 ]'
sage: backend.ascii_art_formatter([1,2,3], concatenate=True).ascii_art.get_
˓→str()
'1 2 3'
default_preferences()
Return the backend’s display preferences
Override this method to change the default preferences when using your backend.
OUTPUT:
Instance of DisplayPreferences.
EXAMPLES:
display_immediately(plain_text, rich_output)
Show output without going back to the command line prompt.
This method is similar to the rich output displayhook(), except that it can be invoked at any time.
Typically, it ends up being called by sage.plot.graphics.Graphics.show().
Derived classes must implement this method.
INPUT:
Same as displayhook().
OUTPUT:
This method may return something so you can implement displayhook() by calling this method.
However, when called by the display manager any potential return value is discarded: There is no way to
return anything without returning to the command prompt.
EXAMPLES:
displayhook(plain_text, rich_output)
Backend implementation of the displayhook
The value of the last statement on a REPL input line or notebook cell are usually handed to the Python
displayhook and shown on screen. By overriding this method you define how your backend handles output.
The difference to the usual displayhook is that Sage already converted the value to the most suitable rich
output container.
Derived classes must implement this method.
INPUT:
• plain_text – instance of OutputPlainText. The plain text version of the output.
• rich_output – instance of an output container class (subclass of OutputBase). Guaranteed
to be one of the output containers returned from supported_output(), possibly the same as
plain_text.
OUTPUT:
This method may return something, which is then returned from the display manager’s displayhook()
method.
EXAMPLES:
get_display_manager()
Return the display manager singleton
This is a convenience method to access the display manager singleton.
OUTPUT:
The unique DisplayManager instance.
EXAMPLES:
install(**kwds)
Hook that will be called once before the backend is used for the first time.
The default implementation does nothing.
INPUT:
• kwds – optional keyword arguments that are passed through by the switch_backend() method.
EXAMPLES:
is_in_terminal()
Test whether the UI is meant to run in a terminal
See sage.repl.rich_output.display_manager.DisplayManager.
is_in_terminal() for details.
OUTPUT:
Defaults to False.
EXAMPLES:
latex_formatter(obj, **kwds)
Hook to override how Latex is being formatted.
INPUT:
• obj – anything.
• **kwds – optional keyword arguments to control the formatting. Supported are:
– concatenate – boolean (default: False). If True, the argument obj must be iterable and
its entries will be concatenated. There is a single whitespace between entries.
OUTPUT:
Instance of OutputLatex containing the latex string representation of the object.
EXAMPLES:
max_width()
Return the number of characters that fit into one output line
OUTPUT:
Integer.
EXAMPLES:
newline()
Return the newline string.
OUTPUT:
String for starting a new line of output.
EXAMPLES:
plain_text_formatter(obj, **kwds)
Hook to override how plain text is being formatted.
If the object does not have a _rich_repr_ method, or if it does not return a rich output object
(OutputBase), then this method is used to generate plain text output.
INPUT:
• obj – anything.
• **kwds – optional keyword arguments to control the formatting. Supported are:
– concatenate – boolean (default: False). If True, the argument obj must be iterable and
its entries will be concatenated. There is a single whitespace between entries.
OUTPUT:
Instance of OutputPlainText containing the string representation of the object.
EXAMPLES:
set_underscore_variable(obj)
Set the _ builtin variable.
By default, this sets the special _ variable. Backends that organize the history differently (e.g. IPython)
can override this method.
INPUT:
• obj – result of the most recent evaluation.
EXAMPLES:
sage: from sage.repl.rich_output.backend_base import BackendBase
sage: backend = BackendBase()
sage: backend.set_underscore_variable(123)
sage: _
123
sage: 'foo'
'foo'
sage: _ # indirect doctest
'foo'
supported_output()
Return the outputs that are supported by the backend.
Subclasses must implement this method.
OUTPUT:
Iterable of output container classes, that is, subclass of OutputBase). May be a list/tuple/set/frozenset.
The order is ignored. Only used internally by the display manager.
You may return backend-specific subclasses of existing output containers. This allows you to attach
backend-specific functionality to the output container.
EXAMPLES:
sage: from sage.repl.rich_output.backend_base import BackendBase
sage: backend = BackendBase()
sage: backend.supported_output()
Traceback (most recent call last):
...
NotImplementedError: derived classes must implement this method
unicode_art_formatter(obj, **kwds)
Hook to override how unicode art is being formatted.
INPUT:
• obj – anything.
• **kwds – optional keyword arguments to control the formatting. Supported are:
– concatenate – boolean (default: False). If True, the argument obj must be iterable and
its entries will be concatenated. There is a single whitespace between entries.
OUTPUT:
Instance of OutputUnicodeArt containing the unicode art string representation of the object.
EXAMPLES:
sage: from sage.repl.rich_output.backend_base import BackendBase
sage: backend = BackendBase()
sage: out = backend.unicode_art_formatter(list(range(30)))
(continues on next page)
'[ 1, 2, 3 ]'
sage: backend.unicode_art_formatter([1,2,3], concatenate=True).unicode_art.
˓→get_str()
'1 2 3'
uninstall()
Hook that will be called once right before the backend is removed.
The default implementation does nothing.
EXAMPLES:
class sage.repl.rich_output.backend_base.BackendSimple
Bases: sage.repl.rich_output.backend_base.BackendBase
Simple Backend
This backend only supports plain text.
EXAMPLES:
display_immediately(plain_text, rich_output)
Show output without going back to the command line prompt.
INPUT:
Same as displayhook().
OUTPUT:
This backend returns nothing, it just prints to stdout.
EXAMPLES:
supported_output()
Return the outputs that are supported by the backend.
OUTPUT:
Iterable of output container classes, that is, subclass of OutputBase). This backend only supports the
plain text output container.
EXAMPLES:
sage: dm._output_promotions
{<class 'sage.repl.rich_output.output_basic.OutputPlainText'>:
<class 'sage.repl.rich_output.backend_test.TestOutputPlainText'>}
sage: dm.displayhook(1/2)
1/2 [TestOutputPlainText]
TestOutputPlainText container
class sage.repl.rich_output.backend_test.BackendTest
Bases: sage.repl.rich_output.backend_base.BackendBase
display_immediately(plain_text, rich_output)
Show output without going back to the command line prompt.
INPUT:
Same as displayhook().
OUTPUT:
This method returns the rich output for doctesting convenience. The actual display framework ignores the
return value.
EXAMPLES:
supported_output()
Return the outputs that are supported by the backend.
OUTPUT:
Iterable of output container classes. Only the TestOutputPlainText output container is supported
by the test backend.
EXAMPLES:
The output of this method is used by the display manager to set up the actual supported outputs. Compare:
sage: list(display_manager.supported_output())
[<class 'sage.repl.rich_output.output_basic.OutputPlainText'>]
class sage.repl.rich_output.backend_test.TestObject
Bases: sage.structure.sage_object.SageObject
Test object with both _repr_() and _rich_repr_()
class sage.repl.rich_output.backend_test.TestOutputPlainText(*args, **kwds)
Bases: sage.repl.rich_output.output_basic.OutputPlainText
Backend-specific subclass of the plain text output container.
Backends must not influence how the display system constructs output containers, they can only control how the
output container is displayed. In particular, we cannot override the constructor (only the OutputPlainText
constructor is used).
EXAMPLES:
print_to_stdout()
Write the data to stdout.
This is just a convenience method to help with debugging.
EXAMPLES:
This backend is active during doctests. It should mimic the behavior of the IPython command line as close as possible.
Without actually launching image viewers, of course.
EXAMPLES:
class sage.repl.rich_output.backend_doctest.BackendDoctest
Bases: sage.repl.rich_output.backend_base.BackendBase
default_preferences()
Return the backend’s display preferences
Matches the IPython command line display preferences to keep the differences between that and the
doctests to a minimum.
OUTPUT:
Instance of DisplayPreferences.
EXAMPLES:
display_immediately(plain_text, rich_output)
Display object immediately
INPUT:
Same as displayhook().
EXAMPLES:
The following example does not call the displayhook. More precisely, the show() method returns None
which is ignored by the displayhook. When running the example on a Sage display backend capable of
displaying graphics outside of the displayhook, the plot is still shown. Nothing is shown during doctests:
displayhook(plain_text, rich_output)
Display object from displayhook
INPUT:
• plain_text – instance of OutputPlainText. The plain text version of the output.
• rich_output – instance of an output container class (subclass of OutputBase). Guaranteed
to be one of the output containers returned from supported_output(), possibly the same as
plain_text.
EXAMPLES:
This ends up calling the displayhook:
install(**kwds)
Switch to the doctest backend.
This method is being called from within switch_backend(). You should never call it by hand.
INPUT:
None of the optional keyword arguments are used in the doctest backend.
EXAMPLES:
supported_output()
Return the supported output types
OUTPUT:
Set of subclasses of OutputBase, the supported output container types.
EXAMPLES:
uninstall()
Switch away from the doctest backend
This method is being called from within switch_backend(). You should never call it by hand.
EXAMPLES:
validate(rich_output)
Perform checks on rich_output
INPUT:
• rich_output – instance of a subclass of OutputBase.
OUTPUT:
An assertion is triggered if rich_output is invalid.
EXAMPLES:
display_immediately(plain_text, rich_output)
Show output immediately.
This method is similar to the rich output displayhook(), except that it can be invoked at any time.
INPUT:
Same as displayhook().
OUTPUT:
This method does not return anything.
EXAMPLES:
install(**kwds)
Switch the Sage rich output to the IPython backend
INPUT:
• shell – keyword argument. The IPython shell.
No tests since switching away from the doctest rich output backend will break the doctests.
EXAMPLES:
set_underscore_variable(obj)
Set the _ builtin variable.
Since IPython handles the history itself, this does nothing.
INPUT:
• obj – anything.
EXAMPLES:
class sage.repl.rich_output.backend_ipython.BackendIPythonCommandline
Bases: sage.repl.rich_output.backend_ipython.BackendIPython
Backend for the IPython Command Line
EXAMPLES:
default_preferences()
Return the backend’s display preferences
The default for the commandline is to not plot graphs since the launching of an external viewer is consid-
ered too disruptive.
OUTPUT:
Instance of DisplayPreferences.
EXAMPLES:
display_immediately(plain_text, rich_output)
Show output without going back to the command line prompt.
This method is similar to the rich output displayhook(), except that it can be invoked at any time. On
the Sage command line it launches viewers just like displayhook().
INPUT:
Same as displayhook().
OUTPUT:
This method does not return anything.
EXAMPLES:
displayhook(plain_text, rich_output)
Backend implementation of the displayhook
INPUT:
• plain_text – instance of OutputPlainText. The plain text version of the output.
• rich_output – instance of an output container class (subclass of OutputBase). Guaranteed
to be one of the output containers returned from supported_output(), possibly the same as
plain_text.
OUTPUT:
The IPython commandline display hook returns the IPython display data, a pair of dictionaries. The
first dictionary contains mime types as keys and the respective output as value. The second dictionary is
metadata.
EXAMPLES:
is_in_terminal()
Test whether the UI is meant to run in a terminal
See sage.repl.rich_output.display_manager.DisplayManager.
is_in_terminal() for details.
OUTPUT:
True for the IPython commandline.
EXAMPLES:
launch_jmol(output_jmol, plain_text)
Launch the stand-alone jmol viewer
INPUT:
• output_jmol – OutputSceneJmol. The scene to launch Jmol with.
• plain_text – string. The plain text representation.
OUTPUT:
String. Human-readable message indicating that the viewer was launched.
EXAMPLES:
launch_viewer(image_file, plain_text)
Launch external viewer for the graphics file.
INPUT:
• image_file – string. File name of the image file.
• plain_text – string. The plain text representation of the image file.
OUTPUT:
String. Human-readable message indicating whether the viewer was launched successfully.
EXAMPLES:
supported_output()
Return the outputs that are supported by the IPython commandline backend.
OUTPUT:
Iterable of output container classes, that is, subclass of OutputBase). The order is ignored.
EXAMPLES:
threejs_offline_scripts()
Three.js scripts for the IPython command line
OUTPUT:
String containing script tags
EXAMPLES:
class sage.repl.rich_output.backend_ipython.BackendIPythonNotebook
Bases: sage.repl.rich_output.backend_ipython.BackendIPython
Backend for the IPython Notebook
EXAMPLES:
sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
sage: BackendIPythonNotebook()
IPython notebook
displayhook(plain_text, rich_output)
Backend implementation of the displayhook
INPUT:
• plain_text – instance of OutputPlainText. The plain text version of the output.
• rich_output – instance of an output container class (subclass of OutputBase). Guaranteed
to be one of the output containers returned from supported_output(), possibly the same as
plain_text.
OUTPUT:
The IPython notebook display hook returns the IPython display data, a pair of dictionaries. The first
dictionary contains mime types as keys and the respective output as value. The second dictionary is
metadata.
EXAMPLES:
sage: from sage.repl.rich_output.output_basic import OutputPlainText
sage: plain_text = OutputPlainText.example()
sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
sage: backend = BackendIPythonNotebook()
sage: backend.displayhook(plain_text, plain_text)
({u'text/plain': u'Example plain text output'}, {})
supported_output()
Return the outputs that are supported by the IPython notebook backend.
OUTPUT:
Iterable of output container classes, that is, subclass of OutputBase). The order is ignored.
EXAMPLES:
sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
sage: backend = BackendIPythonNotebook()
sage: supp = backend.supported_output(); supp # random output
set([<class 'sage.repl.rich_output.output_graphics.OutputPlainText'>,
...,
<class 'sage.repl.rich_output.output_graphics.OutputImagePdf'>])
sage: from sage.repl.rich_output.output_basic import OutputLatex
sage: OutputLatex in supp
True
(continues on next page)
threejs_offline_scripts()
Three.js scripts for the IPython notebook
OUTPUT:
String containing script tags
EXAMPLES:
SIX
MISCELLANEOUS
This module contains all of Sage’s customizations to the IPython interpreter. These changes consist of the following
major components:
• SageTerminalApp
• SageInteractiveShell
• SageTerminalInteractiveShell
• interface_shell_embed()
6.1.1 SageTerminalApp
This is the main application object. It is used by the $SAGE_LOCAL/bin/sage-ipython script to start the Sage
command-line. It’s primary purpose is to
• Initialize the SageTerminalInteractiveShell.
• Provide default configuration options for the shell, and its subcomponents. These work with (and can be over-
ridden by) IPython’s configuration system.
• Load the Sage ipython extension (which does things like preparsing, add magics, etc.).
• Provide a custom SageCrashHandler to give the user instructions on how to report the crash to the Sage
support mailing list.
6.1.2 SageInteractiveShell
The SageInteractiveShell object is the object responsible for accepting input from the user and evaluating it.
From the command-line, this object can be retrieved by running:
Any input is preprocessed and evaluated inside the shell.run_cell method. If the command line processing does
not do what you want it to do, you can step through it in the debugger:
91
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
6.1.3 SageTerminalInteractiveShell
The function interface_shell_embed() takes a Interface object and returns an embeddable IPython
shell which can be used to directly interact with that shell. The bulk of this functionality is provided through
InterfaceShellTransformer.
class sage.repl.interpreter.InterfaceShellTransformer(*args, **kwds)
Bases: IPython.core.prefilter.PrefilterTransformer
Initialize this class. All of the arguments get passed to PrefilterTransformer.__init__().
temporary_objects
a list of hold onto interface objects and keep them from being garbage collected
See also:
interface_shell_embed()
preparse_imports_from_sage(line)
Finds occurrences of strings such as sage(object) in line, converts object to shell.interface,
and replaces those strings with their identifier in the new system. This also works with strings such as
maxima(object) if shell.interface is maxima.
Parameters line (string) – the line to transform
EXAMPLES:
Since trac ticket #28439, this also works with more complicated expressions containing nested parentheses:
92 Chapter 6. Miscellaneous
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
transform(line, continue_prompt)
Evaluates line in shell.interface and returns a string representing the result of that evaluation.
Parameters
• line (string) – the line to be transformed and evaluated
• continue_prompt (bool) – is this line a continuation in a sequence of multiline in-
put?
EXAMPLES:
'sage.misc.all.logstr(r"""4""")'
sage: ift.shell.ex('a = 4')
sage: ift.transform(r'sage(a)+4', False)
'sage.misc.all.logstr(r"""8""")'
sage: ift.temporary_objects
set()
sage: shell = interface_shell_embed(gap)
sage: ift = InterfaceShellTransformer(shell=shell, config=shell.config,
˓→prefilter_manager=shell.prefilter_manager)
class sage.repl.interpreter.SageCrashHandler(app)
Bases: IPython.terminal.ipapp.IPAppCrashHandler
A custom CrashHandler which gives the user instructions on how to post the problem to sage-support.
EXAMPLES:
class sage.repl.interpreter.SageNotebookInteractiveShell(ipython_dir=None,
profile_dir=None,
user_module=None,
user_ns=None, cus-
tom_exceptions=((),
None), **kwargs)
Bases: sage.repl.interpreter.SageShellOverride, IPython.core.
interactiveshell.InteractiveShell
IPython Shell for the Sage IPython Notebook
The doctests are not tested since they would change the current rich output backend away from the doctest rich
output backend.
EXAMPLES:
init_display_formatter()
Switch to the Sage IPython notebook rich output backend
EXAMPLES:
sage.repl.interpreter.SagePreparseTransformer(**kwargs)
EXAMPLES:
sage.repl.interpreter.SagePromptTransformer(**kwargs)
Strip the sage:/. . . .: prompts of Sage.
EXAMPLES:
The prompt contains a trailing space. Extra spaces between the last prompt and the remainder should not be
stripped:
We test that the input transformer is enabled on the Sage command line:
94 Chapter 6. Miscellaneous
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
class sage.repl.interpreter.SageShellOverride
Bases: object
Mixin to override methods in IPython’s [Terminal]InteractiveShell classes.
show_usage()
Print the basic Sage usage.
This method ends up being called when you enter ? and nothing else on the command line.
EXAMPLES:
system_raw(cmd)
Run a system command.
This is equivalent to the sage-native-execute shell script.
EXAMPLES:
class sage.repl.interpreter.SageTerminalApp(**kwargs)
Bases: IPython.terminal.ipapp.TerminalIPythonApp
crash_handler_class
alias of SageCrashHandler
init_shell()
Initialize the SageInteractiveShell instance.
EXAMPLES:
load_config_file(*args, **kwds)
Merges a config file with the default sage config.
shell_class
A trait whose value must be a subclass of a specified class.
test_shell
A boolean (True, False) trait.
class sage.repl.interpreter.SageTerminalInteractiveShell(*args, **kwargs)
Bases: sage.repl.interpreter.SageShellOverride, IPython.terminal.
interactiveshell.TerminalInteractiveShell
IPython Shell for the Sage IPython Commandline Interface
The doctests are not tested since they would change the current rich output backend away from the doctest rich
output backend.
EXAMPLES:
init_display_formatter()
Switch to the Sage IPython commandline rich output backend
EXAMPLES:
96 Chapter 6. Miscellaneous
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
init_display_formatter()
Switch to the Sage IPython commandline rich output backend
EXAMPLES:
quit()
Quit the test shell.
To make the test shell as realistic as possible, we switch to the BackendIPythonCommandline dis-
play backend. This method restores the previous display backend, which is the BackendDoctest during
doctests.
EXAMPLES:
sage: shell.quit()
sage: get_display_manager()
The Sage display manager using the doctest backend
run_cell(*args, **kwds)
Run IPython cell
Starting with IPython-3.0, this returns an success/failure information. Since it is more convenient for
doctests, we ignore it.
EXAMPLES:
sage.repl.interpreter.embedded()
Returns True if Sage is being run from the notebook.
EXAMPLES:
sage.repl.interpreter.get_test_shell()
Returns a IPython shell that can be used in testing the functions in this module.
OUTPUT:
An IPython shell
EXAMPLES:
sage.repl.interpreter.interface_shell_embed(interface)
Returns an IPython shell which uses a Sage interface on the backend to perform the evaluations. It uses
InterfaceShellTransformer to transform the input into the appropriate interface.eval(...)
input.
INPUT:
• interface – A Sage PExpect interface instance.
EXAMPLES:
˓→ false ]>
sage.repl.interpreter.preparser(on=True)
Turn on or off the Sage preparser.
Parameters on (bool) – if True turn on preparsing; if False, turn it off.
EXAMPLES:
sage: 2/3
2/3
sage: preparser(False)
sage: 2/3 # not tested since doctests are always preparsed
0
sage: preparser(True)
sage: 2^3
8
98 Chapter 6. Miscellaneous
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
init_environment()
Set up Sage command-line environment
init_inspector()
init_line_transforms()
Set up transforms (like the preparser).
register_interface_magics()
Register magics for each of the Sage interfaces
run_init()
Run Sage’s initial startup file.
set_quit_hook()
Set the exit hook to cleanly exit Sage.
class sage.repl.ipython_extension.SageJupyterCustomizations(shell=None)
Bases: sage.repl.ipython_extension.SageCustomizations
static all_globals()
Return a Python module containing all globals which should be made available to the user when running
the Jupyter notebook.
EXAMPLES:
sage: from sage.repl.ipython_extension import SageJupyterCustomizations
sage: SageJupyterCustomizations.all_globals()
<module 'sage.repl.ipython_kernel.all_jupyter' ...>
Note that the doctests are never really at the command prompt, so we call the input hook manually:
sage: shell.run_cell('from sage.repl.attach import reload_attached_files_if_
˓→modified')
sage: shell.run_cell('reload_attached_files_if_modified()')
### reloading attached file run_cell.py modified at ... ###
sage: shell.run_cell('a')
3
sage: shell.run_cell('detach(%r)'%tmp)
sage: shell.run_cell('attached_files()')
[]
sage: os.remove(tmp)
sage: shell.quit()
crun(s)
Profile C function calls
INPUT:
• s – string. Sage command to profile.
EXAMPLES:
sage: from sage.repl.interpreter import get_test_shell
sage: shell = get_test_shell()
sage: shell.run_cell('%crun sum(1/(1+n^2) for n in range(100))') # optional
˓→- gperftools
(continues on next page)
cython(line, cell)
Cython cell magic
This is syntactic sugar on the cython_compile() function.
INPUT:
• line – ignored.
• cell – string. The Cython source code to process.
OUTPUT:
None. The Cython code is compiled and loaded.
EXAMPLES:
display(args)
A magic command to switch between simple display and ASCII art display.
• args – string. See sage.misc.display_hook.DisplayHookBase.set_display() for
allowed values. If the mode is ascii_art, it can optionally be followed by a width.
How to use: if you want to activate the ASCII art mode:
That means you do not have to use ascii_art() to get an ASCII art output:
Sometime you could have to use a special output width and you could specify it:
[ 1 3 4 1 2 4 1 2 3 1 3 1 2 2 2
[ 1 2 3 4, 2 , 3 , 4 , 2 4, 3 4, 3 , 4
˓→ ,
1 ]
1 2 2 ]
3 3 ]
4 , 4 ]
sage: shell.run_cell('%display ascii_art 50')
sage: shell.run_cell('StandardTableaux(4).list()')
[
[
[ 1 3 4 1 2 4 1 2 3
[ 1 2 3 4, 2 , 3 , 4 ,
1 ]
1 4 1 3 1 2 2 ]
1 3 1 2 2 2 3 3 ]
2 4, 3 4, 3 , 4 , 4 , 4 ]
As yet another option, typeset mode. This is used in the emacs interface:
sage: shell.run_cell('%display text latex')
sage: shell.run_cell('1/2')
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2}
Switch back:
sage: shell.run_cell('%display default')
fortran(line, cell)
Fortran cell magic.
This is syntactic sugar on the fortran() function.
INPUT:
• line – ignored.
• cell – string. The Cython source code to process.
OUTPUT:
None. The Fortran code is compiled and loaded.
EXAMPLES:
sage: from sage.repl.interpreter import get_test_shell
sage: shell = get_test_shell()
sage: shell.run_cell('''
....: %%fortran
(continues on next page)
iload(args)
A magic command to interactively load a file as in MAGMA.
• args – string. The file to be interactively loaded
EXAMPLES:
runfile(s)
Execute the code contained in the file s.
This is designed to be used from the command line as %runfile /path/to/file.
• s – string. The file to be loaded.
EXAMPLES:
sage: import os
sage: from sage.repl.interpreter import get_test_shell
sage: from sage.misc.all import tmp_dir
sage: shell = get_test_shell()
(continues on next page)
sage.repl.ipython_extension.load_ipython_extension(*args, **kwargs)
Load the extension in IPython.
sage.repl.ipython_extension.run_once(func)
Runs a function (successfully) only once.
The running can be reset by setting the has_run attribute to False
This module defines magic functions for interpreters. As an example, consider the GAP interpreter which can evaluate
a gap command given as a string:
Magics are syntactic sugar to avoid writing the Python string. They are either called as line magics:
Note that the cell magic needs semicolons, this is required by the GAP language to separate multiple commands.
class sage.repl.interface_magic.InterfaceMagic(name, interface)
Bases: object
Interface Magic
This class is a wrapper around interface objects to provide them with magics.
INPUT:
• name – string. The interface name
• interface – sage.interfaces.expect.Expect. The interface to wrap.
EXAMPLES:
classmethod all_iter()
Iterate over the available interfaces
EXAMPLES:
cell_magic_factory()
Factory for cell magic
OUTPUT:
A function suitable to be used as cell magic.
EXAMPLES:
sage: shell.run_cell('%%gap?')
Docstring:
Interact with gap
The cell magic %%gap sends multiple lines to the gap interface.
...
classmethod find(name)
Find a particular magic by name
This method is for doctesting purposes only.
INPUT:
• name – string. The name of the interface magic to search for.
OUTPUT:
The corresponding InterfaceMagic instance.
EXAMPLES:
line_magic_factory()
Factory for line magic
OUTPUT:
A function suitable to be used as line magic.
EXAMPLES:
The line magic %gap sends a single line to the gap interface.
...
classmethod register_all(shell=None)
Register all available interfaces
EXAMPLES:
This is mostly the same as the stock ipywidgets.interact, but with some customizations for Sage.
EXAMPLES:
sage: from sage.repl.ipython_kernel.interact import interact
sage: @interact
....: def f(x=(0,10)):
....: pass
Interactive function <function f at ...> with 1 widget
x: IntSlider(value=5, description=u'x', max=10)
sage: f.widget.children
(IntSlider(value=5, description=u'x', max=10), Output())
signature()
Return the fixed signature of the interactive function (after a possible auto_update parameter was
removed).
EXAMPLES:
sage: from sage.repl.ipython_kernel.interact import sage_interactive
sage: def myfunc(x=[1,2,3], auto_update=False): pass
sage: sage_interactive(myfunc).signature().parameters # py2
OrderedDict([('x', <Parameter ... 'x'>)])
sage: sage_interactive(myfunc).signature().parameters # py3
mappingproxy({'x': <Parameter "x=[1, 2, 3]">})
˓→EvalText(value=u'3', layout=Layout(max_width=u'5em')))),
˓→VBox(children=(EvalText(value=u'2', layout=Layout(max_width=u'5em')),
˓→EvalText(value=u'4', layout=Layout(max_width=u'5em'))))))
sage: sage_interactive.widget_from_single_value(Color('cornflowerblue'))
SageColorPicker(value='#6495ed')
These are all based on widgets from ipywidgets, changing or combining existing widgets.
class sage.repl.ipython_kernel.widgets.EvalText(*args, **kwds)
Bases: sage.repl.ipython_kernel.widgets.EvalWidget, ipywidgets.widgets.
widget_string.Text
A ipywidgets.Text widget which evaluates (using sage_eval()) its contents and applies an optional
transformation.
EXAMPLES:
get_value()
Evaluate the bare widget value using sage_eval().
EXAMPLES:
˓→VBox(children=(Text(value=u'0,1'), Text(value=u'1,1')))))
sage: w.get_interact_value()
[[u'0,0', u'0,1'], [u'1,0', u'1,1']]
description
A trait for unicode strings.
value
An instance of a Python list.
class sage.repl.ipython_kernel.widgets.HTMLText(value=None, **kwargs)
Bases: ipywidgets.widgets.widget_string.HTMLMath
An HTML widget whose description is always empty.
This is used to display arbitrary HTML text in interacts without a label. The text_control() function from
SageNB is an alias of HTMLText.
EXAMPLES:
description
Always return empty string.
EXAMPLES:
class sage.repl.ipython_kernel.widgets.SageColorPicker(**kwargs)
Bases: ipywidgets.widgets.widget_color.ColorPicker
A color picker widget returning a Sage Color.
EXAMPLES:
get_interact_value()
Return a Sage Color corresponding to the value of this widget.
EXAMPLES:
class sage.repl.ipython_kernel.widgets.TransformFloatRangeSlider(*args,
**kwds)
Bases: sage.repl.ipython_kernel.widgets.TransformWidget, ipywidgets.widgets.
widget_float.FloatRangeSlider
An ipywidgets.FloatRangeSlider widget with an optional transformation.
EXAMPLES:
sage: w
TransformFloatRangeSlider(value=(7.0, 9.0))
sage: w.get_interact_value()
2.0
sage: w
TransformFloatSlider(value=7.0)
sage: w.get_interact_value()
2.6457513110645907
sage: w
TransformIntRangeSlider(value=(7, 9))
sage: w.get_interact_value()
2
get_interact_value()
Return the transformed value of this widget, by calling the transform function.
EXAMPLES:
get_value()
Return self.value.
This is meant to be overridden by sub-classes to change the input of the transform function.
EXAMPLES:
6.6. Functions to construct widgets, based on the old SageNB interface. 113
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
sage.repl.ipython_kernel.widgets_sagenb.checkbox(default=True, label=None)
A checkbox widget.
INPUT:
• default – (boolean) initial value
• label – optional label
EXAMPLES:
sage.repl.ipython_kernel.widgets_sagenb.input_box(default=None, label=None,
type=None, width=80, height=1)
A textbox widget.
INPUT:
• default – initial value
• label – optional label
• type – function of one variable or None. if type is str, the value of this widget for interactive functions
is just the text as str. Otherwise, the text is evaluated using sage_eval(), type is called on it and
the result is used as value. Except if type is None, then the evaluated text is used as value.
• width – width of the box
• height – if height > 1, create a textarea instead of a single-line textbox.
EXAMPLES:
sage: w.get_interact_value()
'4+5'
sage: w = input_box("4+5")
sage: w
EvalText(value=u'4+5', layout=Layout(max_width=u'81em'))
sage: w.get_interact_value()
9
With a different type, the text is evaluated and type is called on it:
sage: w = input_box(“4+5”, type=float) sage: w EvalText(value=u‘4+5’, lay-
out=Layout(max_width=u‘81em’)) sage: w.get_interact_value() 9.0
Despite the keyword name, type does not need to be a type:
6.6. Functions to construct widgets, based on the old SageNB interface. 115
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
EXAMPLES:
˓→EvalText(value=u'42', layout=Layout(max_width=u'5em')))),
˓→VBox(children=(EvalText(value=u'42', layout=Layout(max_width=u'5em')),
˓→EvalText(value=u'42', layout=Layout(max_width=u'5em'))))))
˓→EvalText(value=u'-sin(x)', layout=Layout(max_width=u'5em')))),
˓→VBox(children=(EvalText(value=u'sin(x)', layout=Layout(max_width=u'5em')),
˓→EvalText(value=u'cos(x)', layout=Layout(max_width=u'5em'))))))
sage: w.get_interact_value()
[ cos(x) sin(x)]
[-sin(x) cos(x)]
sage: w = input_grid(2, 2, default=[1, x, x^2, x^3], to_value=lambda x: x[1][1]);
˓→w
˓→EvalText(value=u'x^2', layout=Layout(max_width=u'5em')))),
˓→VBox(children=(EvalText(value=u'x', layout=Layout(max_width=u'5em')),
˓→EvalText(value=u'x^3', layout=Layout(max_width=u'5em'))))))
sage: w.get_interact_value()
x^3
sage.repl.ipython_kernel.widgets_sagenb.range_slider(*args, **kwds)
A slider widget to select a range of values.
INPUT:
• vmin, vmax – minimum and maximum value
• step_size – the step size
• default – initial value, given as a 2-tuple
• label – optional label
• display_value – (boolean) if True, display the current value.
EXAMPLES:
sage: w = range_slider(5); w
TransformIntRangeSlider(value=(28, 76), min=5)
(continues on next page)
Apart from a simple list, values can be given as a list of 2-tuples (value, label):
sage: selector([(1,"one"), (2,"two"), (3,"three")])
Dropdown(options=(('one', 1), ('two', 2), ('three', 3)), value=1)
sage: selector([(1,"one"), (2,"two"), (3,"three")], buttons=True)
ToggleButtons(options=(('one', 1), ('two', 2), ('three', 3)), value=1)
A dict of label:value pairs is also allowed. Since a dict is not ordered, it is better to use an
OrderedDict:
sage: from collections import OrderedDict
sage: selector(OrderedDict(one=1, two=2, three=3)) # py2
Dropdown(options=OrderedDict([('one', 1), ('three', 3), ('two', 2)]), value=1)
sage: selector(OrderedDict(one=1, two=2, three=3)) # py3
Dropdown(options=OrderedDict([('one', 1), ('two', 2), ('three', 3)]), value=1)
sage: selector(OrderedDict(one=1, two=2, three=3), buttons=True) # py2
(continues on next page)
6.6. Functions to construct widgets, based on the old SageNB interface. 117
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
sage: w = slider(5); w
TransformIntSlider(value=5, min=5)
sage: parent(w.get_interact_value())
Integer Ring
sage: w = slider(int(5)); w
IntSlider(value=5, min=5)
sage: parent(w.get_interact_value())
<... 'int'>
sage: w = slider(5, 20, step_size=RDF("0.1")); w
TransformFloatSlider(value=5.0, max=20.0, min=5.0)
sage: parent(w.get_interact_value())
(continues on next page)
sage: parent(w.get_interact_value())
Real Field with 53 bits of precision
For a selection slider, the default is adjusted to one of the possible values:
Kernels have to register themselves with Jupyter so that they appear in the Jupyter notebook’s kernel drop-down. This
is done by SageKernelSpec.
Note: The doctests in this module run in a temporary directory as the involved directories might be different during
runs of the tests and actual installation and because we might be lacking write permission to places such as /usr/
share.
class sage.repl.ipython_kernel.install.SageKernelSpec(prefix=None)
Bases: object
Utility to manage SageMath kernels and extensions
INPUT:
• prefix – (optional, default: sys.prefix) directory for the installation prefix
EXAMPLES:
classmethod identifier()
Internal identifier for the SageMath kernel
OUTPUT: the string "sagemath".
EXAMPLES:
kernel_spec()
Return the kernel spec as Python dictionary
OUTPUT:
A dictionary. See the Jupyter documentation for details.
EXAMPLES:
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec.kernel_spec()
{'argv': ..., 'display_name': 'SageMath ...', 'language': 'sage'}
symlink(src, dst)
Symlink src to dst
This is not an atomic operation.
Already-existing symlinks will be deleted, already existing non-empty directories will be kept.
EXAMPLES:
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: path = tmp_dir()
sage: spec.symlink(os.path.join(path, 'a'), os.path.join(path, 'b'))
sage: os.listdir(path)
['b']
use_local_jsmol()
Symlink jsmol to the Jupyter notebook.
EXAMPLES:
sage: from sage.repl.ipython_kernel.install import SageKernelSpec
sage: spec = SageKernelSpec(prefix=tmp_dir())
sage: spec.use_local_jsmol()
sage: jsmol = os.path.join(spec.nbextensions_dir, 'jsmol')
sage: os.path.isdir(jsmol)
True
sage: os.path.isfile(os.path.join(jsmol, "JSmol.min.js"))
True
use_local_mathjax()
Symlink SageMath’s Mathjax install to the Jupyter notebook.
EXAMPLES:
use_local_threejs()
Symlink threejs to the Jupyter notebook.
EXAMPLES:
sage.repl.ipython_kernel.install.have_prerequisites(debug=True)
Check that we have all prerequisites to run the Jupyter notebook.
In particular, the Jupyter notebook requires OpenSSL whether or not you are using https. See trac ticket #17318.
INPUT:
debug – boolean (default: True). Whether to print debug information in case that prerequisites are missing.
OUTPUT:
Boolean.
EXAMPLES:
Version of the Jupyter kernel when running Sage inside the Jupyter notebook or remote Jupyter sessions.
class sage.repl.ipython_kernel.kernel.SageKernel(**kwds)
Bases: ipykernel.ipkernel.IPythonKernel
The Sage Jupyter Kernel
INPUT:
See the Jupyter documentation
EXAMPLES:
banner
The Sage Banner
The value of this property is displayed in the Jupyter notebook.
OUTPUT:
String.
EXAMPLES:
help_links
Help in the Jupyter Notebook
OUTPUT:
See the Jupyter documentation.
Note: Urls starting with “kernelspecs” are prepended by the browser with the appropriate path.
EXAMPLES:
pre_handler_hook()
Restore the signal handlers to their default values at Sage startup, saving the old handler at the
saved_sigint_handler attribute. This is needed because Jupyter needs to change the SIGINT
handler.
See trac ticket #19135.
shell_class
A trait whose value must be a subclass of a specified class.
class sage.repl.ipython_kernel.kernel.SageZMQInteractiveShell(ipython_dir=None,
profile_dir=None,
user_module=None,
user_ns=None,
cus-
tom_exceptions=((),
None),
**kwargs)
Bases: sage.repl.interpreter.SageNotebookInteractiveShell, ipykernel.
zmqshell.ZMQInteractiveShell
First, test the pinfo magic for Python code. This is what IPython calls when you ask for the single-questionmark help,
like 𝑓 𝑜𝑜?
INPUT:
EXAMPLES:
...
Init docstring: ...ee help(type(...)) for...signature...
File: .../sage/repl/ipython_tests.py
Type: function
EXAMPLES:
...
Init docstring: ...ee help(type(...)) for...signature...
File: .../sage/tests/stl_vector.pyx
Type: type
Next, test the pinfo magic for R interface code, see trac ticket #26906:
Next, test the pinfo2 magic for Python code. This is what IPython calls when you ask for the double-questionmark
help, like 𝑓 𝑜𝑜??
INPUT:
EXAMPLES::
...
"""
return 'Source code would be here'
File: .../sage/repl/ipython_tests.py
Type: function
EXAMPLES::
...
"""
def __cinit__(self):
"""
The Cython constructor.
EXAMPLES::
(continues on next page)
...
File: .../sage/tests/stl_vector.pyx
Type: type
Next, test the pinfo2 magic for R interface code, see trac ticket #26906:
sage.repl.ipython_tests.dummy(argument, optional=None)
Dummy Docstring Title
Dummy docstring explanation.
INPUT:
• argument – anything. Dummy argument.
• optional – anything (optional). Dummy optional.
EXAMPLES:
This is all an evil iframe hack to get JSmol to display 3-d graphics while separating JSmol’s j2s machinery from your
actual web page.
There are some caveats for how to load JSmol, in particular it cannot just load its code from a file:// uri. To use a
html file generated by this module, you need
• A web server,
• The JSmol directory tree must be served by your web server,
• The output of JSMolHtml.inner_html() or JSMolHtml.outer_html() must be served by the same
web server.
See https://github.com/phetsims/molecule-polarity/issues/6 for a discussion of loading JSMol.
iframe()
Return HTML iframe
OUTPUT:
String.
EXAMPLES:
inner_html()
Return a HTML document containing a JSmol applet
EXAMPLES:
js_script()
The script() as Javascript string.
Since the many shortcomings of Javascript include multi-line strings, this actually returns Javascript code
to reassemble the script from a list of strings.
OUTPUT:
String. Javascript code that evaluates to script() as Javascript string.
EXAMPLES:
outer_html()
Return a HTML document containing an iframe with a JSmol applet
OUTPUT:
String
EXAMPLES:
<iframe srcdoc="
...
</html>
script()
Return the JMol script file.
This method extracts the Jmol script from the Jmol spt file (a zip archive) and inlines meshes.
OUTPUT:
String.
EXAMPLES:
Some computations in Sage return bitmap images, for example matrices can be turned into bitmaps directly. Note that
this is different from all plotting functionality, the latter can equally produce vector graphics. This module is about
bitmaps only, and a shallow wrapper around PIL.Image. The only difference is that Image is displayed as graphics
by the Sage if the UI can.
EXAMPLES:
height()
Return the vertical dimension in pixels
OUTPUT:
Integer.
EXAMPLES:
mode()
Return the color mode
OUTPUT:
String. As given when constructing the image.
EXAMPLES:
pil
Access the wrapped PIL(low) Image
OUTPUT:
The underlying PIL.Image.Image object.
EXAMPLES:
pixels()
Return the pixel map
OUTPUT:
The PIL PixelAccess object that allows you to get/set the pixel data.
EXAMPLES:
save(filename)
Save the bitmap image
INPUT:
• filename – string. The filename to save as. The given extension automatically determines the
image file type.
EXAMPLES:
show()
Show this image immediately.
This method attempts to display the graphics immediately, without waiting for the currently running code
(if any) to return to the command line. Be careful, calling it from within a loop will potentially launch a
large number of external viewer programs.
OUTPUT:
This method does not return anything. Use save() if you want to save the figure as an image.
EXAMPLES:
width()
Return the horizontal dimension in pixels
OUTPUT:
Integer.
EXAMPLES:
This lets us perform actions while IPython is sitting at the terminal input prompt. We use it to reload attached files if
they have changed.
sage.repl.inputhook.install()
Install the Sage input hook
EXAMPLES:
sage.repl.inputhook.sage_inputhook(context)
sage.repl.inputhook.uninstall()
Uninstall the Sage input hook
EXAMPLES:
SEVEN
• Index
• Module Index
• Search Page
133
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
m
sage.misc.trace, 8
r
sage.repl.attach, 28
sage.repl.display.fancy_repr, 39
sage.repl.display.formatter, 35
sage.repl.display.jsmol_iframe, 125
sage.repl.display.pretty_print, 37
sage.repl.display.util, 42
sage.repl.image, 128
sage.repl.inputhook, 130
sage.repl.interface_magic, 104
sage.repl.interpreter, 91
sage.repl.ipython_extension, 99
sage.repl.ipython_kernel.install, 119
sage.repl.ipython_kernel.interact, 107
sage.repl.ipython_kernel.kernel, 121
sage.repl.ipython_kernel.widgets, 109
sage.repl.ipython_kernel.widgets_sagenb, 113
sage.repl.ipython_tests, 123
sage.repl.load, 25
sage.repl.preparse, 11
sage.repl.rich_output.backend_base, 73
sage.repl.rich_output.backend_doctest, 82
sage.repl.rich_output.backend_ipython, 85
sage.repl.rich_output.backend_test, 80
sage.repl.rich_output.buffer, 55
sage.repl.rich_output.display_manager, 45
sage.repl.rich_output.output_basic, 58
sage.repl.rich_output.output_catalog, 72
sage.repl.rich_output.output_graphics, 62
sage.repl.rich_output.output_graphics3d, 66
sage.repl.rich_output.output_video, 70
sage.repl.rich_output.preferences, 50
135
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
Symbols
$PATH, 3
__call__() (sage.repl.display.fancy_repr.LargeMatrixHelpRepr method), 39
__call__() (sage.repl.display.fancy_repr.ObjectReprABC method), 40
__call__() (sage.repl.display.fancy_repr.PlainPythonRepr method), 40
__call__() (sage.repl.display.fancy_repr.SomeIPythonRepr method), 41
__call__() (sage.repl.display.fancy_repr.TallListRepr method), 41
__call__() (sage.repl.display.util.TallListFormatter method), 42
A
add_attached_file() (in module sage.repl.attach), 28
all_globals() (sage.repl.ipython_extension.SageCustomizations static method), 99
all_globals() (sage.repl.ipython_extension.SageJupyterCustomizations static method), 99
all_iter() (sage.repl.interface_magic.InterfaceMagic class method), 104
ascii_art_formatter() (sage.repl.rich_output.backend_base.BackendBase method), 73
attach() (in module sage.repl.attach), 28
attach() (sage.repl.ipython_extension.SageMagics method), 100
attached_files() (in module sage.repl.attach), 29
available_options() (sage.repl.rich_output.preferences.PreferencesABC method), 53
B
BackendBase (class in sage.repl.rich_output.backend_base), 73
BackendDoctest (class in sage.repl.rich_output.backend_doctest), 82
BackendIPython (class in sage.repl.rich_output.backend_ipython), 85
BackendIPythonCommandline (class in sage.repl.rich_output.backend_ipython), 86
BackendIPythonNotebook (class in sage.repl.rich_output.backend_ipython), 89
BackendSimple (class in sage.repl.rich_output.backend_base), 79
BackendTest (class in sage.repl.rich_output.backend_test), 80
banner (sage.repl.ipython_kernel.kernel.SageKernel attribute), 121
BROWSER, 8
C
cell_magic_factory() (sage.repl.interface_magic.InterfaceMagic method), 105
check_backend_class() (sage.repl.rich_output.display_manager.DisplayManager method), 45
checkbox() (in module sage.repl.ipython_kernel.widgets_sagenb), 114
color_selector() (in module sage.repl.ipython_kernel.widgets_sagenb), 114
containing_block() (in module sage.repl.preparse), 14
137
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
D
default_mime() (sage.repl.display.formatter.SageDisplayFormatter method), 36
default_preferences() (sage.repl.rich_output.backend_base.BackendBase method), 74
default_preferences() (sage.repl.rich_output.backend_doctest.BackendDoctest method), 82
default_preferences() (sage.repl.rich_output.backend_ipython.BackendIPythonCommandline method), 86
deleter() (sage.repl.rich_output.preferences.Property method), 53
description (sage.repl.ipython_kernel.widgets.Grid attribute), 110
description (sage.repl.ipython_kernel.widgets.HTMLText attribute), 110
detach() (in module sage.repl.attach), 30
display() (sage.repl.ipython_extension.SageMagics method), 101
display_equation() (sage.repl.rich_output.output_basic.OutputLatex method), 59
display_immediately() (sage.repl.rich_output.backend_base.BackendBase method), 74
display_immediately() (sage.repl.rich_output.backend_base.BackendSimple method), 79
display_immediately() (sage.repl.rich_output.backend_doctest.BackendDoctest method), 82
display_immediately() (sage.repl.rich_output.backend_ipython.BackendIPython method), 85
display_immediately() (sage.repl.rich_output.backend_ipython.BackendIPythonCommandline method), 86
display_immediately() (sage.repl.rich_output.backend_test.BackendTest method), 80
display_immediately() (sage.repl.rich_output.display_manager.DisplayManager method), 46
DisplayException, 45
displayhook() (sage.repl.rich_output.backend_base.BackendBase method), 74
displayhook() (sage.repl.rich_output.backend_doctest.BackendDoctest method), 83
displayhook() (sage.repl.rich_output.backend_ipython.BackendIPythonCommandline method), 87
displayhook() (sage.repl.rich_output.backend_ipython.BackendIPythonNotebook method), 89
displayhook() (sage.repl.rich_output.display_manager.DisplayManager method), 46
DisplayManager (class in sage.repl.rich_output.display_manager), 45
DisplayPreferences (class in sage.repl.rich_output.preferences), 51
DOT_SAGE, 7, 8
dummy() (in module sage.repl.ipython_tests), 125
E
embedded() (in module sage.repl.interpreter), 97
environment variable
$PATH, 3
BROWSER, 8
DOT_SAGE, 7, 8
IPYTHONDIR, 8
JUPYTER_CONFIG_DIR, 8
MPLCONFIGDIR, 8
PATH, 7
SAGE_CHECK, 5
SAGE_CHECK_PACKAGES, 5
SAGE_RC_FILE, 7, 8
SAGE_SERVER, 8
SAGE_STARTUP_FILE, 7, 8
EvalText (class in sage.repl.ipython_kernel.widgets), 109
EvalTextarea (class in sage.repl.ipython_kernel.widgets), 109
138 Index
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
F
filename() (sage.repl.rich_output.buffer.OutputBuffer method), 55
find() (sage.repl.interface_magic.InterfaceMagic class method), 105
format() (sage.repl.display.formatter.SageDisplayFormatter method), 36
format_string() (sage.repl.display.fancy_repr.ObjectReprABC method), 40
fortran() (sage.repl.ipython_extension.SageMagics method), 102
from_file() (sage.repl.rich_output.buffer.OutputBuffer class method), 56
G
get() (sage.repl.rich_output.buffer.OutputBuffer method), 56
get_display_manager() (sage.repl.rich_output.backend_base.BackendBase method), 75
get_instance() (sage.repl.rich_output.display_manager.DisplayManager class method), 47
get_interact_value() (sage.repl.ipython_kernel.widgets.SageColorPicker method), 111
get_interact_value() (sage.repl.ipython_kernel.widgets.TransformWidget method), 113
get_str() (sage.repl.rich_output.buffer.OutputBuffer method), 56
get_test_shell() (in module sage.repl.interpreter), 98
get_unicode() (sage.repl.rich_output.buffer.OutputBuffer method), 57
get_value() (sage.repl.ipython_kernel.widgets.EvalWidget method), 109
get_value() (sage.repl.ipython_kernel.widgets.TransformWidget method), 113
getter() (sage.repl.rich_output.preferences.Property method), 54
graphics (sage.repl.rich_output.preferences.DisplayPreferences attribute), 51
graphics_from_save() (sage.repl.rich_output.display_manager.DisplayManager method), 47
Grid (class in sage.repl.ipython_kernel.widgets), 110
H
handle_encoding_declaration() (in module sage.repl.preparse), 15
have_prerequisites() (in module sage.repl.ipython_kernel.install), 121
height() (sage.repl.image.Image method), 129
help_links (sage.repl.ipython_kernel.kernel.SageKernel attribute), 122
html_fragment() (sage.repl.rich_output.output_graphics.OutputImageGif method), 63
html_fragment() (sage.repl.rich_output.output_video.OutputVideoBase method), 71
HTMLText (class in sage.repl.ipython_kernel.widgets), 110
Index 139
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
I
identifier() (sage.repl.ipython_kernel.install.SageKernelSpec class method), 119
iframe() (sage.repl.display.jsmol_iframe.JSMolHtml method), 126
iload() (sage.repl.ipython_extension.SageMagics method), 103
Image (class in sage.repl.image), 128
implicit_mul() (in module sage.repl.preparse), 16
implicit_multiplication() (in module sage.repl.preparse), 16
in_quote() (in module sage.repl.preparse), 17
init_display_formatter() (sage.repl.interpreter.SageNotebookInteractiveShell method), 94
init_display_formatter() (sage.repl.interpreter.SageTerminalInteractiveShell method), 96
init_display_formatter() (sage.repl.interpreter.SageTestShell method), 97
init_environment() (sage.repl.ipython_extension.SageCustomizations method), 99
init_inspector() (sage.repl.ipython_extension.SageCustomizations method), 99
init_line_transforms() (sage.repl.ipython_extension.SageCustomizations method), 99
init_shell() (sage.repl.interpreter.SageTerminalApp method), 95
inline_equation() (sage.repl.rich_output.output_basic.OutputLatex method), 60
inner_html() (sage.repl.display.jsmol_iframe.JSMolHtml method), 126
input_box() (in module sage.repl.ipython_kernel.widgets_sagenb), 114
input_grid() (in module sage.repl.ipython_kernel.widgets_sagenb), 115
install() (in module sage.repl.inputhook), 130
install() (sage.repl.rich_output.backend_base.BackendBase method), 75
install() (sage.repl.rich_output.backend_doctest.BackendDoctest method), 83
install() (sage.repl.rich_output.backend_ipython.BackendIPython method), 85
interface_shell_embed() (in module sage.repl.interpreter), 98
InterfaceMagic (class in sage.repl.interface_magic), 104
InterfaceShellTransformer (class in sage.repl.interpreter), 92
IPYTHONDIR, 8
is_in_terminal() (sage.repl.rich_output.backend_base.BackendBase method), 75
is_in_terminal() (sage.repl.rich_output.backend_ipython.BackendIPythonCommandline method), 87
is_in_terminal() (sage.repl.rich_output.display_manager.DisplayManager method), 47
is_loadable_filename() (in module sage.repl.load), 25
isalphadigit_() (in module sage.repl.preparse), 17
J
js_script() (sage.repl.display.jsmol_iframe.JSMolHtml method), 126
JSMolHtml (class in sage.repl.display.jsmol_iframe), 125
JUPYTER_CONFIG_DIR, 8
K
kernel_spec() (sage.repl.ipython_kernel.install.SageKernelSpec method), 120
L
LargeMatrixHelpRepr (class in sage.repl.display.fancy_repr), 39
latex_formatter() (sage.repl.rich_output.backend_base.BackendBase method), 76
launch_jmol() (sage.repl.rich_output.backend_ipython.BackendIPythonCommandline method), 87
launch_script_filename() (sage.repl.rich_output.output_graphics3d.OutputSceneJmol method), 67
launch_viewer() (sage.repl.rich_output.backend_ipython.BackendIPythonCommandline method), 88
line_magic_factory() (sage.repl.interface_magic.InterfaceMagic method), 106
load() (in module sage.repl.load), 25
load_attach_mode() (in module sage.repl.attach), 30
140 Index
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
M
mathjax() (sage.repl.rich_output.output_basic.OutputLatex method), 60
max_width() (sage.repl.rich_output.backend_base.BackendBase method), 76
mode() (sage.repl.image.Image method), 129
modified_file_iterator() (in module sage.repl.attach), 32
MPLCONFIGDIR, 8
mtllib() (sage.repl.rich_output.output_graphics3d.OutputSceneWavefront method), 69
N
newline() (sage.repl.rich_output.backend_base.BackendBase method), 77
O
obj_filename() (sage.repl.rich_output.output_graphics3d.OutputSceneWavefront method), 69
ObjectReprABC (class in sage.repl.display.fancy_repr), 39
outer_html() (sage.repl.display.jsmol_iframe.JSMolHtml method), 127
OutputAsciiArt (class in sage.repl.rich_output.output_basic), 58
OutputBase (class in sage.repl.rich_output.output_basic), 59
OutputBuffer (class in sage.repl.rich_output.buffer), 55
OutputImageDvi (class in sage.repl.rich_output.output_graphics), 62
OutputImageGif (class in sage.repl.rich_output.output_graphics), 63
OutputImageJpg (class in sage.repl.rich_output.output_graphics), 64
OutputImagePdf (class in sage.repl.rich_output.output_graphics), 64
OutputImagePng (class in sage.repl.rich_output.output_graphics), 65
OutputImageSvg (class in sage.repl.rich_output.output_graphics), 65
OutputLatex (class in sage.repl.rich_output.output_basic), 59
OutputPlainText (class in sage.repl.rich_output.output_basic), 61
OutputSceneCanvas3d (class in sage.repl.rich_output.output_graphics3d), 66
OutputSceneJmol (class in sage.repl.rich_output.output_graphics3d), 67
OutputSceneThreejs (class in sage.repl.rich_output.output_graphics3d), 68
OutputSceneWavefront (class in sage.repl.rich_output.output_graphics3d), 68
OutputTypeException, 49
OutputUnicodeArt (class in sage.repl.rich_output.output_basic), 61
OutputVideoAvi (class in sage.repl.rich_output.output_video), 70
OutputVideoBase (class in sage.repl.rich_output.output_video), 70
OutputVideoFlash (class in sage.repl.rich_output.output_video), 71
OutputVideoMatroska (class in sage.repl.rich_output.output_video), 71
OutputVideoMp4 (class in sage.repl.rich_output.output_video), 71
OutputVideoOgg (class in sage.repl.rich_output.output_video), 72
OutputVideoQuicktime (class in sage.repl.rich_output.output_video), 72
OutputVideoWebM (class in sage.repl.rich_output.output_video), 72
OutputVideoWmv (class in sage.repl.rich_output.output_video), 72
P
parse_ellipsis() (in module sage.repl.preparse), 17
Index 141
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
PATH, 7
pil (sage.repl.image.Image attribute), 129
pixels() (sage.repl.image.Image method), 129
plain_text_formatter() (sage.repl.rich_output.backend_base.BackendBase method), 77
PlainPythonRepr (class in sage.repl.display.fancy_repr), 40
pre_handler_hook() (sage.repl.ipython_kernel.kernel.SageKernel method), 122
preferences (sage.repl.rich_output.display_manager.DisplayManager attribute), 48
PreferencesABC (class in sage.repl.rich_output.preferences), 52
preparse() (in module sage.repl.preparse), 18
preparse_calculus() (in module sage.repl.preparse), 19
preparse_file() (in module sage.repl.preparse), 20
preparse_file_named() (in module sage.repl.preparse), 20
preparse_file_named_to_stream() (in module sage.repl.preparse), 20
preparse_generators() (in module sage.repl.preparse), 20
preparse_imports_from_sage() (sage.repl.interpreter.InterfaceShellTransformer method), 92
preparse_numeric_literals() (in module sage.repl.preparse), 21
preparser() (in module sage.repl.interpreter), 98
pretty() (sage.repl.display.pretty_print.SagePrettyPrinter method), 38
print_to_stdout() (sage.repl.rich_output.backend_test.TestOutputPlainText method), 81
print_to_stdout() (sage.repl.rich_output.output_basic.OutputAsciiArt method), 58
print_to_stdout() (sage.repl.rich_output.output_basic.OutputLatex method), 60
print_to_stdout() (sage.repl.rich_output.output_basic.OutputPlainText method), 61
print_to_stdout() (sage.repl.rich_output.output_basic.OutputUnicodeArt method), 62
Property (class in sage.repl.rich_output.preferences), 53
Python Enhancement Proposals
PEP 263, 16
Q
quit() (sage.repl.interpreter.SageTestShell method), 97
R
range_slider() (in module sage.repl.ipython_kernel.widgets_sagenb), 116
register_all() (sage.repl.interface_magic.InterfaceMagic class method), 106
register_interface_magics() (sage.repl.ipython_extension.SageCustomizations method), 99
reload_attached_files_if_modified() (in module sage.repl.attach), 32
reset() (in module sage.repl.attach), 33
reset_load_attach_path() (in module sage.repl.attach), 33
restricted_output (class in sage.repl.rich_output.display_manager), 50
RichReprWarning, 50
run_cell() (sage.repl.interpreter.SageTestShell method), 97
run_init() (sage.repl.ipython_extension.SageCustomizations method), 99
run_once() (in module sage.repl.ipython_extension), 104
runfile() (sage.repl.ipython_extension.SageMagics method), 103
S
sage.misc.trace (module), 8
sage.repl.attach (module), 28
sage.repl.display.fancy_repr (module), 39
sage.repl.display.formatter (module), 35
sage.repl.display.jsmol_iframe (module), 125
142 Index
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
sage.repl.display.pretty_print (module), 37
sage.repl.display.util (module), 42
sage.repl.image (module), 128
sage.repl.inputhook (module), 130
sage.repl.interface_magic (module), 104
sage.repl.interpreter (module), 91
sage.repl.ipython_extension (module), 99
sage.repl.ipython_kernel.install (module), 119
sage.repl.ipython_kernel.interact (module), 107
sage.repl.ipython_kernel.kernel (module), 121
sage.repl.ipython_kernel.widgets (module), 109
sage.repl.ipython_kernel.widgets_sagenb (module), 113
sage.repl.ipython_tests (module), 123
sage.repl.load (module), 25
sage.repl.preparse (module), 11
sage.repl.rich_output.backend_base (module), 73
sage.repl.rich_output.backend_doctest (module), 82
sage.repl.rich_output.backend_ipython (module), 85
sage.repl.rich_output.backend_test (module), 80
sage.repl.rich_output.buffer (module), 55
sage.repl.rich_output.display_manager (module), 45
sage.repl.rich_output.output_basic (module), 58
sage.repl.rich_output.output_catalog (module), 72
sage.repl.rich_output.output_graphics (module), 62
sage.repl.rich_output.output_graphics3d (module), 66
sage.repl.rich_output.output_video (module), 70
sage.repl.rich_output.preferences (module), 50
SAGE_CHECK, 5
SAGE_CHECK_PACKAGES, 5
sage_inputhook() (in module sage.repl.inputhook), 131
sage_interactive (class in sage.repl.ipython_kernel.interact), 107
SAGE_RC_FILE, 7, 8
SAGE_SERVER, 8
SAGE_STARTUP_FILE, 7, 8
SageColorPicker (class in sage.repl.ipython_kernel.widgets), 111
SageCrashHandler (class in sage.repl.interpreter), 93
SageCustomizations (class in sage.repl.ipython_extension), 99
SageDisplayFormatter (class in sage.repl.display.formatter), 36
SageJupyterCustomizations (class in sage.repl.ipython_extension), 99
SageKernel (class in sage.repl.ipython_kernel.kernel), 121
SageKernelSpec (class in sage.repl.ipython_kernel.install), 119
SageMagics (class in sage.repl.ipython_extension), 100
SageNotebookInteractiveShell (class in sage.repl.interpreter), 93
SagePlainTextFormatter (class in sage.repl.display.formatter), 37
SagePreparseTransformer() (in module sage.repl.interpreter), 94
SagePrettyPrinter (class in sage.repl.display.pretty_print), 38
SagePromptTransformer() (in module sage.repl.interpreter), 94
SageShellOverride (class in sage.repl.interpreter), 95
SageTerminalApp (class in sage.repl.interpreter), 95
SageTerminalInteractiveShell (class in sage.repl.interpreter), 96
Index 143
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
T
TallListFormatter (class in sage.repl.display.util), 42
TallListRepr (class in sage.repl.display.fancy_repr), 41
temporary_objects (sage.repl.interpreter.InterfaceShellTransformer attribute), 92
test_shell (sage.repl.interpreter.SageTerminalApp attribute), 96
TestObject (class in sage.repl.rich_output.backend_test), 81
TestOutputPlainText (class in sage.repl.rich_output.backend_test), 81
text (sage.repl.rich_output.preferences.DisplayPreferences attribute), 52
threejs_offline_scripts() (sage.repl.rich_output.backend_ipython.BackendIPythonCommandline
method), 88
threejs_offline_scripts() (sage.repl.rich_output.backend_ipython.BackendIPythonNotebook method), 90
threejs_scripts() (sage.repl.rich_output.display_manager.DisplayManager method), 49
toplevel() (sage.repl.display.pretty_print.SagePrettyPrinter method), 38
trace() (in module sage.misc.trace), 8
transform() (sage.repl.interpreter.InterfaceShellTransformer method), 92
TransformFloatRangeSlider (class in sage.repl.ipython_kernel.widgets), 111
TransformFloatSlider (class in sage.repl.ipython_kernel.widgets), 111
TransformIntRangeSlider (class in sage.repl.ipython_kernel.widgets), 111
TransformIntSlider (class in sage.repl.ipython_kernel.widgets), 112
144 Index
Sage 9.1 Reference Manual: The Sage Command Line, Release 9.1
U
unicode_art_formatter() (sage.repl.rich_output.backend_base.BackendBase method), 78
uninstall() (in module sage.repl.inputhook), 131
uninstall() (sage.repl.rich_output.backend_base.BackendBase method), 79
uninstall() (sage.repl.rich_output.backend_doctest.BackendDoctest method), 84
update() (sage.repl.ipython_kernel.install.SageKernelSpec class method), 120
use_local_jsmol() (sage.repl.ipython_kernel.install.SageKernelSpec method), 120
use_local_mathjax() (sage.repl.ipython_kernel.install.SageKernelSpec method), 120
use_local_threejs() (sage.repl.ipython_kernel.install.SageKernelSpec method), 121
V
validate() (sage.repl.rich_output.backend_doctest.BackendDoctest method), 84
value (sage.repl.ipython_kernel.widgets.Grid attribute), 110
W
widget_from_iterable() (sage.repl.ipython_kernel.interact.sage_interactive class method), 107
widget_from_single_value() (sage.repl.ipython_kernel.interact.sage_interactive class method), 108
widget_from_tuple() (sage.repl.ipython_kernel.interact.sage_interactive class method), 108
width() (sage.repl.image.Image method), 130
Index 145