desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Switch to the desired mode. If mode is not specified, cycles through the available modes.'
def set_mode(self, mode=None):
if (not mode): new_idx = ((self.valid_modes.index(self.mode) + 1) % len(self.valid_modes)) self.mode = self.valid_modes[new_idx] elif (mode not in self.valid_modes): raise ValueError(((('Unrecognized mode in FormattedTB: <' + mode) + '>\nValid modes: ') + str(self.valid...
'Print out a formatted exception traceback. Optional arguments: - out: an open file-like object to direct output to. - tb_offset: the number of frames to skip over in the stack, on a per-call basis (this overrides temporarily the instance\'s tb_offset given at initialization time.'
def __call__(self, etype=None, evalue=None, etb=None, out=None, tb_offset=None):
if (out is None): out = self.ostream out.flush() out.write(self.text(etype, evalue, etb, tb_offset)) out.write('\n') out.flush() try: self.debugger() except KeyboardInterrupt: print '\nKeyboardInterrupt'
'Return the current error state and clear it'
def clear_err_state(self):
e = self.last_syntax_error self.last_syntax_error = None return e
'Convert a structured traceback (a list) to a string.'
def stb2text(self, stb):
return ''.join(stb)
'Test magic_run_completer, should match two alterntives'
def test_1(self):
event = MockEvent(u'%run a') mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {u'a.py', u'aao.py', u'adir/'})
'Test magic_run_completer, should match one alterntive'
def test_2(self):
event = MockEvent(u'%run aa') mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {u'aao.py'})
'Test magic_run_completer with unterminated "'
def test_3(self):
event = MockEvent(u'%run "a') mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {u'a.py', u'aao.py', u'adir/'})
'Test magic_run_completer, should match two alterntives'
@onlyif_unicode_paths def test_1(self):
event = MockEvent(u'%run a') mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {u'a.py', u'aa\xf8.py'})
'Test magic_run_completer, should match one alterntive'
@onlyif_unicode_paths def test_2(self):
event = MockEvent(u'%run aa') mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {u'aa\xf8.py'})
'Test magic_run_completer with unterminated "'
@onlyif_unicode_paths def test_3(self):
event = MockEvent(u'%run "a') mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {u'a.py', u'aa\xf8.py'})
'Test that cells with only naked strings are fully executed'
def test_naked_string_cells(self):
ip.run_cell('"a"\n') self.assertEqual(ip.user_ns['_'], 'a') ip.run_cell('"""a\nb"""\n') self.assertEqual(ip.user_ns['_'], 'a\nb')
'Just make sure we don\'t get a horrible error with a blank cell of input. Yes, I did overlook that.'
def test_run_empty_cell(self):
old_xc = ip.execution_count res = ip.run_cell('') self.assertEqual(ip.execution_count, old_xc) self.assertEqual(res.execution_count, None)
'Multi-block, multi-line cells must execute correctly.'
def test_run_cell_multiline(self):
src = '\n'.join(['x=1', 'y=2', 'if 1:', ' x += 1', ' y += 1']) res = ip.run_cell(src) self.assertEqual(ip.user_ns['x'], 2) self.assertEqual(ip.user_ns['y'], 3) self.assertEqual(res.success, True) self.assertEqual(res.result, None)
'Code sprinkled with multiline strings should execute (GH-306)'
def test_multiline_string_cells(self):
ip.run_cell('tmp=0') self.assertEqual(ip.user_ns['tmp'], 0) res = ip.run_cell('tmp=1;"""a\nb"""\n') self.assertEqual(ip.user_ns['tmp'], 1) self.assertEqual(res.success, True) self.assertEqual(res.result, 'a\nb')
'Ending a line with semicolon should not cache the returned object (GH-307)'
def test_dont_cache_with_semicolon(self):
oldlen = len(ip.user_ns['Out']) for cell in ['1;', '1;1;']: res = ip.run_cell(cell, store_history=True) newlen = len(ip.user_ns['Out']) self.assertEqual(oldlen, newlen) self.assertIsNone(res.result) i = 0 for cell in ['1', '1;1']: ip.run_cell(cell, store_history=T...
'Verify that In variable grows with user input (GH-284)'
def test_In_variable(self):
oldlen = len(ip.user_ns['In']) ip.run_cell('1;', store_history=True) newlen = len(ip.user_ns['In']) self.assertEqual((oldlen + 1), newlen) self.assertEqual(ip.user_ns['In'][(-1)], '1;')
'test that running !(command) does not raise a SyntaxError'
def test_trailing_newline(self):
ip.run_cell('!(true)\n', False) ip.run_cell('!(true)\n\n\n', False)
'Pretty-printing lists of objects with non-ascii reprs may cause problems.'
def test_gh_597(self):
class Spam(object, ): def __repr__(self): return ('\xe9' * 50) import IPython.core.formatters f = IPython.core.formatters.PlainTextFormatter() f([Spam(), Spam()])
'Check that future flags are used for parsing code (gh-777)'
def test_future_flags(self):
ip.run_cell('from __future__ import barry_as_FLUFL') try: ip.run_cell('prfunc_return_val = 1 <> 2') assert ('prfunc_return_val' in ip.user_ns) finally: ip.compile.reset_compiler_flags()
'Can we pickle objects defined interactively (GH-29)'
def test_can_pickle(self):
ip = get_ipython() ip.reset() ip.run_cell('class Mylist(list):\n def __init__(self,x=[]):\n list.__init__(self,x)') ip.run_cell('w=Mylist([1,2,3])') from pickle import dumps _main = sys.modules['__main__'] sys.modules['__main__'] = ip.user_...
'Code in functions must be able to access variables outside them.'
def test_global_ns(self):
ip = get_ipython() ip.run_cell('a = 10') ip.run_cell('def f(x):\n return x + a') ip.run_cell('b = f(12)') self.assertEqual(ip.user_ns['b'], 22)
'Check that InteractiveShell is protected from bad custom exception handlers'
def test_bad_custom_tb(self):
ip.set_custom_exc((IOError,), (lambda etype, value, tb: (1 / 0))) self.assertEqual(ip.custom_exceptions, (IOError,)) with tt.AssertPrints('Custom TB Handler failed', channel='stderr'): ip.run_cell(u'raise IOError("foo")') self.assertEqual(ip.custom_exceptions, ())
'Check that InteractiveShell is protected from bad return types in custom exception handlers'
def test_bad_custom_tb_return(self):
ip.set_custom_exc((NameError,), (lambda etype, value, tb, tb_offset=None: 1)) self.assertEqual(ip.custom_exceptions, (NameError,)) with tt.AssertPrints('Custom TB Handler failed', channel='stderr'): ip.run_cell(u'a=abracadabra') self.assertEqual(ip.custom_exceptions, ())
'Test local variable expansion in !system and %magic calls'
def test_var_expand_local(self):
ip.run_cell('def test():\n lvar = "ttt"\n ret = !echo {lvar}\n return ret[0]\n') res = ip.user_ns['test']() nt.assert_in('ttt', res) ip.run_cell('def makemacro():\n macroname = "macro_var_expand_locals"\n ...
'Test variable expansion with the name \'self\', which was failing. See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218'
def test_var_expand_self(self):
ip.run_cell('class cTest:\n classvar="see me"\n def test(self):\n res = !echo Variable: {self.classvar}\n return res[0]\n') nt.assert_in('see me', ip.user_ns['cTest']().test())
'var_expand on invalid formats shouldn\'t raise'
def test_bad_var_expand(self):
self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}") self.assertEqual(ip.var_expand(u'{asdf}'), u'{asdf}') self.assertEqual(ip.var_expand(u'{1/0}'), u'{1/0}')
'run_cell(silent=True) doesn\'t invoke pre/post_run_cell callbacks'
def test_silent_postexec(self):
pre_explicit = mock.Mock() pre_always = mock.Mock() post_explicit = mock.Mock() post_always = mock.Mock() ip.events.register('pre_run_cell', pre_explicit) ip.events.register('pre_execute', pre_always) ip.events.register('post_run_cell', post_explicit) ip.events.register('post_execute', p...
'run_cell(silent=True) doesn\'t advance execution_count'
def test_silent_noadvance(self):
ec = ip.execution_count ip.run_cell('1', store_history=True, silent=True) self.assertEqual(ec, ip.execution_count) ip.run_cell('1', store_history=True) self.assertEqual((ec + 1), ip.execution_count)
'run_cell(silent=True) doesn\'t trigger displayhook'
def test_silent_nodisplayhook(self):
d = dict(called=False) trap = ip.display_trap save_hook = trap.hook def failing_hook(*args, **kwargs): d['called'] = True try: trap.hook = failing_hook res = ip.run_cell('1', silent=True) self.assertFalse(d['called']) self.assertIsNone(res.result) ip.r...
'Check that last execution result gets set correctly (GH-10702)'
def test_last_execution_result(self):
result = ip.run_cell('a = 5; a') self.assertTrue(ip.last_execution_succeeded) self.assertEqual(ip.last_execution_result.result, 5) result = ip.run_cell('a = x_invalid_id_x') self.assertFalse(ip.last_execution_succeeded) self.assertFalse(ip.last_execution_result.success) self.a...
'Test safe_execfile with non-ascii path'
@onlyif_unicode_paths def test_1(self):
ip.safe_execfile(self.fname, {}, raise_exceptions=True)
'Test system_raw with non-ascii cmd'
@onlyif_unicode_paths def test_1(self):
cmd = u'python -c "\'\xe5\xe4\xf6\'" ' ip.system_raw(cmd)
'Test we\'re not loading modules on startup that we shouldn\'t.'
def test_extraneous_loads(self):
self.mktmp("import sys\nprint('numpy' in sys.modules)\nprint('ipyparallel' in sys.modules)\nprint('ipykernel' in sys.modules)\n") out = 'False\nFalse\nFalse\n' tt.ipexec_validate(self.fname, out)
'Check that NodeTransformers can reject input.'
def test_input_rejection(self):
expect_exception_tb = tt.AssertPrints('InputRejected: test') expect_no_cell_output = tt.AssertNotPrints("'unsafe'", suppress=False) with expect_exception_tb: with expect_no_cell_output: ip.run_cell("'unsafe'") with expect_exception_tb: with expect_no_cell_output: ...
'Make a valid python temp file.'
def setup(self):
self.mktmp('\nimport warnings\ndef wrn():\n warnings.warn(\n "I AM A WARNING",\n DeprecationWarning\n )\n')
'No deprecation warning should be raised from imported functions'
def test_no_dep(self):
ip.run_cell('from {} import wrn'.format(self.fname)) with tt.AssertNotPrints('I AM A WARNING'): ip.run_cell('wrn()') ip.run_cell('del wrn')
'Test that `__file__` is set when running `ipython file.py`'
def test_py_script_file_attribute(self):
src = 'print(__file__)\n' self.mktmp(src) err = (SQLITE_NOT_AVAILABLE_ERROR if sqlite_err_maybe else None) tt.ipexec_validate(self.fname, self.fname, err)
'Test that `__file__` is set when running `ipython file.ipy`'
def test_ipy_script_file_attribute(self):
src = 'print(__file__)\n' self.mktmp(src, ext='.ipy') err = (SQLITE_NOT_AVAILABLE_ERROR if sqlite_err_maybe else None) tt.ipexec_validate(self.fname, self.fname, err)
'Test that `__file__` is not set after `ipython -i file.py`'
@dec.skip_win32 def test_py_script_file_attribute_interactively(self):
src = 'True\n' self.mktmp(src) (out, err) = tt.ipexec(self.fname, options=['-i'], commands=['"__file__" in globals()', 'exit()']) self.assertIn('False', out)
'Traceback produced if the line where the error occurred is missing? https://github.com/ipython/ipython/issues/1456'
def test_changing_py_file(self):
with TemporaryDirectory() as td: fname = os.path.join(td, 'foo.py') with open(fname, 'w') as f: f.write(file_1) with prepended_to_syspath(td): ip.run_cell('import foo') with tt.AssertPrints('ZeroDivisionError'): ip.run_cell('foo.f()') wi...
'Test with only spaces as split chars.'
def test_spaces(self):
self.sp.delims = ' ' t = [('foo', '', 'foo'), ('run foo', '', 'foo'), ('run foo', 'bar', 'foo')] check_line_split(self.sp, t)
'Test issue #2108.'
def test_line_continuation(self):
isp = self.isp isp.push('1 \\\n\n') self.assertEqual(isp.push_accepts_more(), False) isp.push('1 \\ ') self.assertEqual(isp.push_accepts_more(), False) isp.push('(1 \\ ') self.assertEqual(isp.push_accepts_more(), False)
'Validate that the given input lines produce the resulting namespace. Note: the input lines are given exactly as they would be typed in an auto-indenting environment, as mini_interactive_loop above already does auto-indenting and prepends spaces to the input.'
def check_ns(self, lines, ns):
src = mini_interactive_loop(pseudo_input(lines)) test_ns = {} exec src in test_ns for (k, v) in ns.items(): self.assertEqual(test_ns[k], v)
'Call all single-line syntax tests from the main object'
def test_syntax(self):
isp = self.isp for example in syntax.values(): for (raw, out_t) in example: if raw.startswith(' '): continue isp.push((raw + '\n')) out_raw = isp.source_raw out = isp.source_reset() self.assertEqual(out.rstrip(), out_t, tt.pa...
'Check that %run doesn\'t damage __builtins__'
def test_builtins_id(self):
_ip = get_ipython() bid1 = id(_ip.user_ns['__builtins__']) self.run_tmpfile() bid2 = id(_ip.user_ns['__builtins__']) nt.assert_equal(bid1, bid2)
'Check that the type of __builtins__ doesn\'t change with %run. However, the above could pass if __builtins__ was already modified to be a dict (it should be a module) by a previous use of %run. So we also check explicitly that it really is a module:'
def test_builtins_type(self):
_ip = get_ipython() self.run_tmpfile() nt.assert_equal(type(_ip.user_ns['__builtins__']), type(sys))
'Test that the option -p, which invokes the profiler, do not crash by invoking execfile'
def test_run_profile(self):
self.run_tmpfile_p()
'Make a valid python temp file.'
def test_run_debug_twice_with_breakpoint(self):
_ip = get_ipython() with tt.fake_input(['b 2', 'c', 'c']): _ip.magic(('run -d %s' % self.fname)) with tt.fake_input(['c']): with tt.AssertNotPrints('KeyError'): _ip.magic(('run -d %s' % self.fname))
'Test that simple class definitions work.'
def test_simpledef(self):
src = 'class foo: pass\ndef f(): return foo()' self.mktmp(src) _ip.magic(('run %s' % self.fname)) _ip.run_cell('t = isinstance(f(), foo)') nt.assert_true(_ip.user_ns['t'])
'Test that object\'s __del__ methods are called on exit.'
def test_obj_del(self):
if (sys.platform == 'win32'): try: import win32api except ImportError: raise SkipTest('Test requires pywin32') src = "class A(object):\n def __del__(self):\n print 'object A deleted'\na = A()\n" ...
'Test that namespace cleanup is not too aggressive GH-238 Returning from another run magic deletes the namespace'
def test_aggressive_namespace_cleanup(self):
with tt.TempFileMixin() as empty: empty.mktmp('') src = ('ip = get_ipython()\nfor i in range(5):\n try:\n ip.magic(%r)\n except NameError as e:\n print(i)\n break\n' % ('run...
'Test that running a second file doesn\'t clobber the first, gh-3547'
def test_run_second(self):
self.mktmp('avar = 1\ndef afunc():\n return avar\n') with tt.TempFileMixin() as empty: empty.mktmp('') _ip.magic(('run %s' % self.fname)) _ip.magic(('run %s' % empty.fname)) nt.assert_equal(_ip.user_ns['afunc'](), 1)
'Check that %run -i still works after %reset (gh-693)'
def test_run_i_after_reset(self):
src = 'yy = zz\n' self.mktmp(src) _ip.run_cell('zz = 23') _ip.magic(('run -i %s' % self.fname)) nt.assert_equal(_ip.user_ns['yy'], 23) _ip.magic('reset -f') _ip.run_cell('zz = 23') _ip.magic(('run -i %s' % self.fname)) nt.assert_equal(_ip.user_ns['yy'...
'Check that files in odd encodings are accepted.'
def test_unicode(self):
mydir = os.path.dirname(__file__) na = os.path.join(mydir, 'nonascii.py') _ip.magic(('run "%s"' % na)) nt.assert_equal(_ip.user_ns['u'], u'\u040e\u0442\u2116\u0424')
'Test handling of `__file__` attribute in `%run <file>.py`.'
def test_run_py_file_attribute(self):
src = 't = __file__\n' self.mktmp(src) _missing = object() file1 = _ip.user_ns.get('__file__', _missing) _ip.magic(('run %s' % self.fname)) file2 = _ip.user_ns.get('__file__', _missing) nt.assert_equal(_ip.user_ns['t'], self.fname) nt.assert_equal(file1, file2)
'Test handling of `__file__` attribute in `%run <file.ipy>`.'
def test_run_ipy_file_attribute(self):
src = 't = __file__\n' self.mktmp(src, ext='.ipy') _missing = object() file1 = _ip.user_ns.get('__file__', _missing) _ip.magic(('run %s' % self.fname)) file2 = _ip.user_ns.get('__file__', _missing) nt.assert_equal(_ip.user_ns['t'], self.fname) nt.assert_equal(file1, file2)
'Test that %run -t -N<N> does not raise a TypeError for N > 1.'
def test_run_formatting(self):
src = 'pass' self.mktmp(src) _ip.magic(('run -t -N 1 %s' % self.fname)) _ip.magic(('run -t -N 10 %s' % self.fname))
'Test the -e option to ignore sys.exit()'
def test_ignore_sys_exit(self):
src = 'import sys; sys.exit(1)' self.mktmp(src) with tt.AssertPrints('SystemExit'): _ip.magic(('run %s' % self.fname)) with tt.AssertNotPrints('SystemExit'): _ip.magic(('run -e %s' % self.fname))
'Test %run notebook.ipynb'
def test_run_nb(self):
from nbformat import v4, writes nb = v4.new_notebook(cells=[v4.new_markdown_cell('The Ultimate Question of Everything'), v4.new_code_cell('answer=42')]) src = writes(nb, version=4) self.mktmp(src, ext='.ipynb') _ip.magic(('run %s' % self.fname)) nt.assert_equal(_ip.user_ns['answer...
'Run submodule that has a relative import statement (#2727).'
def test_run_submodule_with_relative_import(self):
self.check_run_submodule('relative')
'Test that references from %run are cleared by xdel.'
def test_xdel(self):
src = 'class A(object):\n monitor = []\n def __del__(self):\n self.monitor.append(1)\na = A()\n' self.mktmp(src) _ip.magic(('run %s' % self.fname)) _ip.run_cell('a') monitor = _ip.user_ns['A'].monitor nt.assert_equ...
'Cell magic using simple decorator'
def test_cell_magic_func_deco(self):
@register_cell_magic def cellm(line, cell): return (line, cell) self.check_ident('cellm')
'Cell magic manually registered'
def test_cell_magic_reg(self):
def cellm(line, cell): return (line, cell) _ip.register_magic_function(cellm, 'cell', 'cellm2') self.check_ident('cellm2')
'Cell magics declared via a class'
def test_cell_magic_class(self):
@magics_class class MyMagics(Magics, ): @cell_magic def cellm3(self, line, cell): return (line, cell) _ip.register_magics(MyMagics) self.check_ident('cellm3')
'Cell magics declared via a class, #2'
def test_cell_magic_class2(self):
@magics_class class MyMagics2(Magics, ): @cell_magic('cellm4') def cellm33(self, line, cell): return (line, cell) _ip.register_magics(MyMagics2) self.check_ident('cellm4') c33 = _ip.find_cell_magic('cellm33') nt.assert_equal(c33, None)
'I am line foo'
@line_magic('foo') def line_foo(self, line):
pass
'I am cell foo, not line foo'
@cell_magic('foo') def cell_foo(self, line, cell):
pass
'Using \'%matplotlib inline\' twice should not reset formatters'
def test_inline_twice(self):
ip = self.Shell() (gui, backend) = ip.enable_matplotlib('inline') nt.assert_equal(gui, 'inline') fmts = {'png'} active_mimes = {_fmt_mime_map[fmt] for fmt in fmts} pt.select_figure_formats(ip, fmts) (gui, backend) = ip.enable_matplotlib('inline') nt.assert_equal(gui, 'inline') for (m...
'Paste input text, by default in quiet mode'
def paste(self, txt, flags='-q'):
ip.hooks.clipboard_get = (lambda : txt) ip.magic(('paste ' + flags))
'Now, test that self.paste -r works'
def test_paste_py_multi_r(self):
self.test_paste_py_multi() nt.assert_equal(ip.user_ns.pop('x'), [1, 2, 3]) nt.assert_equal(ip.user_ns.pop('y'), [1, 4, 9]) nt.assert_false(('x' in ip.user_ns)) ip.magic('paste -r') nt.assert_equal(ip.user_ns['x'], [1, 2, 3]) nt.assert_equal(ip.user_ns['y'], [1, 4, 9])
'Test pasting of email-quoted contents'
def test_paste_email(self):
self.paste(' >> def foo(x):\n >> return x + 1\n >> xx = foo(1.1)') nt.assert_equal(ip.user_ns['xx'], 2.1)
'Email again; some programs add a space also at each quoting level'
def test_paste_email2(self):
self.paste(' > > def foo(x):\n > > return x + 1\n > > yy = foo(2.1) ') nt.assert_equal(ip.user_ns['yy'], 3.1)
'Email quoting of interactive input'
def test_paste_email_py(self):
self.paste(' >> >>> def f(x):\n >> ... return x+1\n >> ... \n >> >>> zz = f(2.5) ') nt.assert_equal(ip.user_ns['zz'], 3.5...
'Also test self.paste echoing, by temporarily faking the writer'
def test_paste_echo(self):
w = StringIO() writer = ip.write ip.write = w.write code = '\n a = 100\n b = 200' try: self.paste(code, '') out = w.getvalue() finally: ip.write = writer nt.assert_equal(ip.user_ns['a'], 100) ...
'Test multiline strings with leading commas'
def test_paste_leading_commas(self):
tm = ip.magics_manager.registry['TerminalMagics'] s = 'a = """\n,1,2,3\n"""' ip.user_ns.pop('foo', None) tm.store_or_execute(s, 'foo') nt.assert_in('foo', ip.user_ns)
'Test pasting sources with trailing question marks'
def test_paste_trailing_question(self):
tm = ip.magics_manager.registry['TerminalMagics'] s = "def funcfoo():\n if True: #am i true?\n return 'fooresult'\n" ip.user_ns.pop('funcfoo', None) self.paste(s) nt.assert_equal(ip.user_ns['funcfoo'](), 'fooresult')
'Add a builtin and save the original.'
def add_builtin(self, key, value):
bdict = builtin_mod.__dict__ orig = bdict.get(key, BuiltinUndefined) if (value is HideBuiltin): if (orig is not BuiltinUndefined): self._orig_builtins[key] = orig del bdict[key] else: self._orig_builtins[key] = orig bdict[key] = value
'Remove an added builtin and re-set the original.'
def remove_builtin(self, key, orig):
if (orig is BuiltinUndefined): del builtin_mod.__dict__[key] else: builtin_mod.__dict__[key] = orig
'Store ipython references in the __builtin__ namespace.'
def activate(self):
add_builtin = self.add_builtin for (name, func) in self.auto_builtins.items(): add_builtin(name, func)
'Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.'
def deactivate(self):
remove_builtin = self.remove_builtin for (key, val) in self._orig_builtins.items(): remove_builtin(key, val) self._orig_builtins.clear() self._builtins_added = False
'Check if the user has set the \'_\' variable by hand.'
def check_for_underscore(self):
if ('_' in builtin_mod.__dict__): try: user_value = self.shell.user_ns['_'] if (user_value is not self._): return del self.shell.user_ns['_'] except KeyError: pass
'Should we silence the display hook because of \';\'?'
def quiet(self):
try: cell = self.shell.history_manager.input_hist_parsed[(-1)] except IndexError: return False sio = _io.StringIO(cell) tokens = list(tokenize.generate_tokens(sio.readline)) for token in reversed(tokens): if (token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tok...
'Start the displayhook, initializing resources.'
def start_displayhook(self):
pass
'Write the output prompt. The default implementation simply writes the prompt to ``sys.stdout``.'
def write_output_prompt(self):
sys.stdout.write(self.shell.separate_out) outprompt = 'Out[{}]: '.format(self.shell.execution_count) if self.do_full_cache: sys.stdout.write(outprompt)
'Compute format data of the object to be displayed. The format data is a generalization of the :func:`repr` of an object. In the default implementation the format data is a :class:`dict` of key value pair where the keys are valid MIME types and the values are JSON\'able data structure containing the raw data for that M...
def compute_format_data(self, result):
return self.shell.display_formatter.format(result)
'Write the format data dict to the frontend. This default version of this method simply writes the plain text representation of the object to ``sys.stdout``. Subclasses should override this method to send the entire `format_dict` to the frontends. Parameters format_dict : dict The format dict for the object passed to `...
def write_format_data(self, format_dict, md_dict=None):
if ('text/plain' not in format_dict): return result_repr = format_dict['text/plain'] if ('\n' in result_repr): if (not self.prompt_end_newline): result_repr = ('\n' + result_repr) print result_repr
'Update user_ns with various things like _, __, _1, etc.'
def update_user_ns(self, result):
if (result is not self.shell.user_ns['_oh']): if ((len(self.shell.user_ns['_oh']) >= self.cache_size) and self.do_full_cache): self.cull_cache() update_unders = True for unders in [('_' * i) for i in range(1, 4)]: if (not (unders in self.shell.user_ns)): ...
'Log the output.'
def log_output(self, format_dict):
if ('text/plain' not in format_dict): return if self.shell.logger.log_output: self.shell.logger.log_write(format_dict['text/plain'], 'output') self.shell.history_manager.output_hist_reprs[self.prompt_count] = format_dict['text/plain']
'Finish up all displayhook activities.'
def finish_displayhook(self):
sys.stdout.write(self.shell.separate_out2) sys.stdout.flush()
'Printing with history cache management. This is invoked everytime the interpreter needs to print, and is activated by setting the variable sys.displayhook to it.'
def __call__(self, result=None):
self.check_for_underscore() if ((result is not None) and (not self.quiet())): self.start_displayhook() self.write_output_prompt() (format_dict, md_dict) = self.compute_format_data(result) self.update_user_ns(result) self.fill_exec_result(result) if format_dict: ...
'Output cache is full, cull the oldest entries'
def cull_cache(self):
oh = self.shell.user_ns.get('_oh', {}) sz = len(oh) cull_count = max(int((sz * self.cull_fraction)), 2) warn('Output cache limit (currently {sz} entries) hit.\nFlushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count)) for (i, n) in enumerate(sorted(oh)):...
'Validate the alias, and return the number of arguments.'
def validate(self):
if (self.name in self.blacklist): raise InvalidAliasError(("The name %s can't be aliased because it is a keyword or builtin." % self.name)) try: caller = self.shell.magics_manager.magics['line'][self.name] except KeyError: pass else: if...
'Define an alias, but don\'t raise on an AliasError.'
def soft_define_alias(self, name, cmd):
try: self.define_alias(name, cmd) except AliasError as e: error(('Invalid alias: %s' % e))
'Define a new alias after validating it. This will raise an :exc:`AliasError` if there are validation problems.'
def define_alias(self, name, cmd):
caller = Alias(shell=self.shell, name=name, cmd=cmd) self.shell.magics_manager.register_function(caller, magic_kind='line', magic_name=name)
'Return an alias, or None if no alias by that name exists.'
def get_alias(self, name):
aname = self.linemagics.get(name, None) return (aname if isinstance(aname, Alias) else None)
'Return whether or not a given name has been defined as an alias'
def is_alias(self, name):
return (self.get_alias(name) is not None)
'Retrieve the command to which an alias expands.'
def retrieve_alias(self, name):
caller = self.get_alias(name) if caller: return caller.cmd else: raise ValueError(('%s is not an alias' % name))
'Command chain is called just like normal func. This will call all funcs in chain with the same args as were given to this function, and return the result of first func that didn\'t raise TryNext'
def __call__(self, *args, **kw):
last_exc = TryNext() for (prio, cmd) in self.chain: try: return cmd(*args, **kw) except TryNext as exc: last_exc = exc raise last_exc
'Add a func to the cmd chain with given priority'
def add(self, func, priority=0):
self.chain.append((priority, func)) self.chain.sort(key=(lambda x: x[0]))
'Return all objects in chain. Handy if the objects are not callable.'
def __iter__(self):
return iter(self.chain)