/usr/lib/python2.7/dist-packages/sagenb/misc/format.py is in python-sagenb 1.0.1+ds1-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | # -*- coding: utf-8 -*-
"""
Code formatting functions for the notebook
Functions used to format code to be used in the notebook.
AUTHORS:
- William Stein (?) - Initial revision
- Tim Dumol (Oct. 16, 2009) - Added additional formatting functions
"""
import ast
import re
from sagenb.misc.misc import unicode_str
_futureimport_re = re.compile(r'((?:from __future__ import [^;\n]+)+)(?:;\s*)?(.*)')
def relocate_future_imports(string):
"""
Relocates imports from __future__ to the beginning of the
file. Raises ``SyntaxError`` if the string does not have proper
syntax.
OUTPUT:
- (string, string) -- a tuple consisting of the string without
``__future__`` imports and the ``__future__`` imports.
EXAMPLES::
sage: from sagenb.misc.format import relocate_future_imports
sage: relocate_future_imports('')
'\n'
sage: relocate_future_imports('foobar')
'\nfoobar'
sage: relocate_future_imports('from __future__ import division\nprint("Hi!")')
'from __future__ import division\n\nprint("Hi!")'
sage: relocate_future_imports('from __future__ import division;print("Testing")')
'from __future__ import division\nprint("Testing")'
sage: relocate_future_imports('from __future__ import division\nprint("Testing!") # from __future__ import division does Blah')
'from __future__ import division\n\nprint("Testing!") # from __future__ import division does Blah'
sage: relocate_future_imports('# -*- coding: utf-8 -*-\nprint("Testing!")\nfrom __future__ import division, operator\nprint("Hey!")')
'from __future__ import division,operator\n# -*- coding: utf-8 -*-\nprint("Testing!")\n\nprint("Hey!")'
"""
lines = string.splitlines()
import_lines = []
parse_tree = ast.parse(string)
future_imports = [x for x in parse_tree.body
if x.__class__ == ast.ImportFrom and
x.module == '__future__']
for imp in future_imports:
line = lines[imp.lineno - 1]
lines[imp.lineno - 1] = line[:imp.col_offset] + re.sub(r'from\s+__future__\s+import\s+%s;?\s*' %
''.join([r'\s*%s\s*,?\s*' % name.name for name in imp.names]),
'', line[imp.col_offset:], 1)
import_lines.append('from __future__ import %s' % ','.join([name.name for name in imp.names]))
return '\n'.join(import_lines) + '\n' + '\n'.join(lines)
def format_for_pexpect(string, prompt, number):
"""
Formats a string for execution by the pexpect WorksheetProcess
implementation.
Currently does the following:
* Adds a magic comment to enable utf-8 encoding
* Moves all __future__ imports to start of file.
* Changes system prompt to `prompt`
* Prints a START message appended with `number`
* Appends `string` after processing with :meth: `displayhook_hack`
EXAMPLES::
sage: from sagenb.misc.format import format_for_pexpect
sage: print(format_for_pexpect('13', 'PROMPT', 1))
# -*- coding: utf-8 -*-
<BLANKLINE>
<BLANKLINE>
import sys
sys.ps1 = "PROMPT"
print("START1")
exec compile(u'13' + '\n', '', 'single')
sage: print(format_for_pexpect('class MyClass:\n def __init__(self):\n pass\na = MyClass()\na', 'PRMPT', 30))
# -*- coding: utf-8 -*-
<BLANKLINE>
<BLANKLINE>
import sys
sys.ps1 = "PRMPT"
print("START30")
class MyClass:
def __init__(self):
pass
a = MyClass()
exec compile(u'a' + '\n', '', 'single')
sage: print(format_for_pexpect('class MyClass:\n def __init__(self):\n pass\n', 'PRMPT', 30))
# -*- coding: utf-8 -*-
<BLANKLINE>
<BLANKLINE>
import sys
sys.ps1 = "PRMPT"
print("START30")
exec compile(u'class MyClass:\n def __init__(self):\n pass' + '\n', '', 'single')
sage: print(format_for_pexpect('from __future__ import division\nprint("Hey!")', 'MYPROMPT', 25))
# -*- coding: utf-8 -*-
from __future__ import division
<BLANKLINE>
import sys
sys.ps1 = "MYPROMPT"
print("START25")
exec compile(u'print("Hey!")' + '\n', '', 'single')
<BLANKLINE>
sage: print(format_for_pexpect('from __future__ import division; print("Hello world!")\nprint("New line!")', 'MYPRMPT', 30))
# -*- coding: utf-8 -*-
from __future__ import division
<BLANKLINE>
import sys
sys.ps1 = "MYPRMPT"
print("START30")
print("Hello world!")
exec compile(u'print("New line!")' + '\n', '', 'single')
"""
string = """
import sys
sys.ps1 = "%s"
print("START%s")
%s
""" % (prompt, number, displayhook_hack(string).encode('utf-8', 'ignore'))
try:
string = '# -*- coding: utf-8 -*-\n' + relocate_future_imports(string)
except SyntaxError:
# Syntax error anyways, so no need to relocate future imports.
string = '# -*- coding: utf-8 -*-\n' + string
return string
def displayhook_hack(string):
"""
Modified version of string so that ``exec``'ing it results in
displayhook possibly being called.
STRING:
- ``string`` - a string
OUTPUT:
- string formated so that when exec'd last line is printed if
it is an expression
EXAMPLES::
sage: from sagenb.misc.format import displayhook_hack
sage: displayhook_hack('\n12\n')
"\nexec compile(u'12' + '\\n', '', 'single')"
sage: displayhook_hack('\ndef my_fun(foo):\n print(foo)\n')
'\ndef my_fun(foo):\n print(foo)'
sage: print(displayhook_hack('\nclass A:\n def __init__(self, foo):\n self.foo\nb = A(8)\nb'))
<BLANKLINE>
class A:
def __init__(self, foo):
self.foo
b = A(8)
exec compile(u'b' + '\n', '', 'single')
"""
# This function is all so the last line (or single lines) will
# implicitly print as they should, unless they are an assignment.
# If anybody knows a better way to do this, please tell me!
string = string.splitlines()
i = len(string)-1
if i >= 0:
while len(string[i]) > 0 and string[i][0] in ' \t':
i -= 1
final_lines = unicode_str('\n'.join(string[i:]))
if not final_lines.startswith('def '):
try:
compile(final_lines + '\n', '', 'single')
string[i] = "exec compile(%r + '\\n', '', 'single')" % final_lines
string = string[:i+1]
except SyntaxError:
pass
return '\n'.join(string)
|