Ticket #12719: 12719-displayhook.patch

File 12719-displayhook.patch, 8.2 KB (added by jason, 9 years ago)
  • sage/all_cmdline.py

    # HG changeset patch
    # User Jason Grout <jason.grout@drake.edu>
    # Date 1347625320 18000
    # Branch ipython
    # Node ID be7b1b4aee1710c33fffa8efe1e7b5a9abc85b6d
    # Parent  1745b8b7b106c820df342144f9b3abd7c2d986dd
    Eliminate unnecessary display hooks (since we now just hook into the IPython display hook).
    
    diff --git a/sage/all_cmdline.py b/sage/all_cmdline.py
    a b  
    1919
    2020    from sage.all import *
    2121    from sage.calculus.predefined import x
    22     preparser(on=True)
    2322
    2423except ValueError as msg:
    2524    import traceback
    2625    t = traceback.format_exc()
    2726    print t
    2827    if 'type object' in str(msg):
    29         msg = str(msg) + '\n\n** In Sage, the easiest fix for this problem is to type "sage -ba"\n   to rebuild all the Cython code (this takes several minutes).\n   Alternatively, touch the last .pyx file in the traceback above. **\n'
     28        msg = str(msg) + """
     29
     30** In Sage, the easiest fix for this problem is to type "sage -ba"
     31   to rebuild all the Cython code (this takes several minutes).
     32   Alternatively, touch the last .pyx file in the traceback above. **
     33"""
    3034    raise ValueError(msg)
    3135
    3236sage.misc.session.init()
    3337
    34 import sage.misc.displayhook
    35 sage.misc.displayhook.install()
    36 
    37 
  • sage/misc/displayhook.py

    diff --git a/sage/misc/displayhook.py b/sage/misc/displayhook.py
    a b  
    1414# This is used to wrap lines when printing "tall" lists.
    1515MAX_COLUMN = 70
    1616
    17 def _check_tall_list_and_print(out_stream, the_list):
     17def _check_tall_list_and_format(the_list):
    1818    """
    19     First check whether a list is "tall" -- whether the reprs of the elements of
    20     the list will span multiple lines and cause the list to be printed awkwardly.
    21     If not, this function returns False and does nothing; you should revert back
    22     to the normal method for printing an object (its repr). If so, return True and
    23     print the list in the special format. Note that the special format isn't just
    24     for matrices. Any object with a multiline repr will be formatted.
     19    First check whether a list is "tall" -- whether the reprs of the
     20    elements of the list will span multiple lines and cause the list
     21    to be printed awkwardly.  If not, this function returns None and
     22    does nothing; you should revert back to the normal method for
     23    printing an object (its repr). If so, return the string in the
     24    special format. Note that the special format isn't just for
     25    matrices. Any object with a multiline repr will be formatted.
    2526
    2627    INPUT:
    2728
    28     - ``out_stream`` - The output stream to use.
    29 
    3029    - ``the_list`` - The list (or a tuple).
    3130
    3231    TESTS::
    3332
    34         sage: import sage.misc.displayhook, sys
     33        sage: from sage.misc.displayhook import format_obj
    3534
    36     We test _check_tall_list_and_print() indirectly by calling print_obj() on
     35    We test _check_tall_list_and_format() indirectly by calling format_obj() on
    3736    a list of matrices::
    3837
    39         sage: sage.misc.displayhook.print_obj(sys.stdout, \
     38        sage: print sage.misc.displayhook.format_obj( \
    4039                [matrix([[1, 2, 3, 4], [5, 6, 7, 8]]) for i in xrange(7)])
    4140        [
    4241        [1 2 3 4]  [1 2 3 4]  [1 2 3 4]  [1 2 3 4]  [1 2 3 4]  [1 2 3 4]
     
    4544        [1 2 3 4]
    4645        [5 6 7 8]
    4746        ]
     47
     48    We return None if we don't have anything special to do::
     49
     50        sage: format_obj('one-line string')
     51        sage: format_obj(matrix([[1,2,3]]))
    4852    """
    4953    # For every object to be printed, split its repr on newlines and store the
    5054    # result in this list.
     
    5660            # Meanwhile, check to make sure the list is actually "tall".
    5761            tall = True
    5862    if not tall:
    59         return False
     63        return None
    6064    # Figure out which type of parenthesis to use, based on the type of the_list.
    6165    if isinstance(the_list, tuple):
    6266        parens = '()'
     
    7175    # and output running_lines using _print_tall_list_row.
    7276    running_lines = [[]]
    7377    current_column = 0
    74     print >>out_stream, parens[0]
     78    s = [parens[0]]
    7579    for split_repr in split_reprs:
    7680        width = max(len(x) for x in split_repr)
    7781        if current_column + width > MAX_COLUMN and not (width > MAX_COLUMN):
    78             _print_tall_list_row(out_stream, running_lines)
     82            s.extend(_tall_list_row(running_lines))
    7983            running_lines = [[]]
    8084            current_column = 0
    8185        current_column += width + 2
     
    9195            running_lines[i].append(' ' * width)
    9296    # Output any remaining entries.
    9397    if len(running_lines[0]) > 0:
    94         _print_tall_list_row(out_stream, running_lines, True)
    95     out_stream.write(str(parens[1]))
    96     return True
     98        s.extend(_tall_list_row(running_lines, True))
     99    s.append(parens[1])
     100    return "\n".join(s)
    97101
    98102# This helper function for _print_tall_list processes and outputs the
    99103# contents of the running_lines array.
    100 def _print_tall_list_row(out_stream, running_lines, last_row=False):
     104def _tall_list_row(running_lines, last_row=False):
     105    s=[]
    101106    for i, line in enumerate(running_lines):
    102107        if i + 1 != len(running_lines):
    103108            sep, tail = '  ', ''
    104109        else:
    105110            # The commas go on the bottom line of this row.
    106111            sep, tail = ', ', '' if last_row else ','
    107         print >>out_stream, sep.join(line) + tail
     112        s.append(sep.join(line) + tail)
    108113    # Separate rows with a newline to make them stand out.
    109114    if not last_row:
    110         print >>out_stream
     115        s.append("")
     116    return s
    111117
    112118def format_obj(obj):
    113119    """
     
    135141        from sage.matrix.matrix import is_Matrix
    136142        from sage.modular.arithgroup.arithgroup_element import ArithmeticSubgroupElement
    137143        if len(obj) > 0 and (is_Matrix(obj[0]) or isinstance(obj[0], ArithmeticSubgroupElement)):
    138             from cStringIO import StringIO
    139             s = StringIO()
    140             if _check_tall_list_and_print(s, obj):
    141                 return s.getvalue()
     144            return _check_tall_list_and_format(obj)
    142145    return None
    143 
    144 def print_obj(out_stream, obj):
    145     """
    146     Return a string if we want to print it in a special way; otherwise, return False.
    147 
    148     EXAMPLES::
    149 
    150         sage: import sage.misc.displayhook, sys
    151 
    152     For most objects, printing is done simply using their repr::
    153 
    154         sage: sage.misc.displayhook.print_obj(sys.stdout, 'Hello, world!')
    155         'Hello, world!'
    156         sage: sage.misc.displayhook.print_obj(sys.stdout, (1, 2, 3, 4))
    157         (1, 2, 3, 4)
    158 
    159     We demonstrate the special format for lists of matrices::
    160 
    161         sage: sage.misc.displayhook.print_obj(sys.stdout, \
    162                 [matrix([[1], [2]]), matrix([[3], [4]])])
    163         [
    164         [1]  [3]
    165         [2], [4]
    166         ]
    167     """
    168     s = format_obj(obj)
    169     if s is None:
    170         s = repr(obj)
    171     print >>out_stream, s
    172 
    173 def displayhook(obj):
    174     """
    175     This function adheres to the displayhook protocol described in `PEP 217`_.
    176     In order to mimic the behavior of the default displayhook, we update the
    177     variable ``__builtin__._`` every time an object is printed.
    178 
    179     .. _`PEP 217`: http://www.python.org/dev/peps/pep-0217/
    180 
    181     TESTS::
    182 
    183         sage: import sage.misc.displayhook, sys
    184         sage: sage.misc.displayhook.displayhook(1)
    185         1
    186         sage: print _
    187         1
    188         sage: sage.misc.displayhook.displayhook(None)
    189         sage: print _
    190         1
    191     """
    192     if obj is None:
    193         return
    194     __builtin__._ = None
    195     print_obj(sys.stdout, obj)
    196     __builtin__._ = obj
    197 
    198 
    199 def install():
    200     """
    201     Install the Sage displayhook into Python
    202 
    203     In a full Sage session, IPython will override this setting later
    204     during the startup. But if you run `from sage.all_cmdline import *`
    205     in a python session, then this function will determine the
    206     displayhook. Importantly, this is what the doctest runner does!
    207    
    208     TESTS::
    209    
    210         sage: sys.displayhook
    211         <function displayhook at 0x...>
    212 
    213     Note that you will get a `sage.misc.interpreter.SageDisplayHook`
    214     object if you run this in an interactive Sage shell. At some point
    215     in the future, the doctest framework will actually run in a Sage
    216     shell and this doctest will change.
    217     """
    218     sys.displayhook = displayhook
    219