From 1c446a83d75a9532577031d082ecc753bd8f1eb7 2016-10-05 21:24:04 From: Pablo Galindo Date: 2016-10-05 21:24:04 Subject: [PATCH] Recovered trailing whitespace --- diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py index 35ed2f7..08382ed 100644 --- a/IPython/core/magics/execution.py +++ b/IPython/core/magics/execution.py @@ -122,7 +122,7 @@ class TimeitTemplateFiller(ast.NodeTransformer): class Timer(timeit.Timer): """Timer class that explicitly uses self.inner - + which is an undocumented implementation detail of CPython, not shared by PyPy. """ @@ -462,7 +462,7 @@ python-profiler package from non-free.""") """Run the named file inside IPython as a program. Usage:: - + %run [-n -i -e -G] [( -t [-N] | -d [-b] | -p [profile options] )] ( -m mod | file ) [args] @@ -657,7 +657,7 @@ python-profiler package from non-free.""") __name__save = self.shell.user_ns['__name__'] prog_ns['__name__'] = '__main__' main_mod = self.shell.user_module - + # Since '%run foo' emulates 'python foo.py' at the cmd line, we must # set the __file__ global in the script's namespace # TK: Is this necessary in interactive mode? @@ -857,7 +857,7 @@ python-profiler package from non-free.""") continue else: break - + except: etype, value, tb = sys.exc_info() @@ -983,7 +983,7 @@ python-profiler package from non-free.""") posix=False, strict=False) if stmt == "" and cell is None: return - + timefunc = timeit.default_timer number = int(getattr(opts, "n", 0)) default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat @@ -1093,16 +1093,16 @@ python-profiler package from non-free.""") The CPU and wall clock times are printed, and the value of the expression (if any) is returned. Note that under Win32, system time is always reported as 0, since it can not be measured. - + This function can be used both as a line and cell magic: - In line mode you can time a single-line statement (though multiple ones can be chained with using semicolons). - - In cell mode, you can time the cell body (a directly + - In cell mode, you can time the cell body (a directly following statement raises an error). - This function provides very basic timing functionality. Use the timeit + This function provides very basic timing functionality. Use the timeit magic for more control over the measurement. Examples @@ -1143,10 +1143,10 @@ python-profiler package from non-free.""") """ # fail immediately if the given expression can't be compiled - + if line and cell: raise UsageError("Can't use statement directly after '%%time'!") - + if cell: expr = self.shell.input_transformer_manager.transform_cell(cell) else: @@ -1196,7 +1196,7 @@ python-profiler package from non-free.""") cpu_user = end[0]-st[0] cpu_sys = end[1]-st[1] cpu_tot = cpu_user+cpu_sys - # On windows cpu_sys is always zero, so no new information to the next print + # On windows cpu_sys is always zero, so no new information to the next print if sys.platform != 'win32': print("CPU times: user %s, sys: %s, total: %s" % \ (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))) @@ -1222,9 +1222,9 @@ python-profiler package from non-free.""") so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed at the command line is used instead. - - -q: quiet macro definition. By default, a tag line is printed - to indicate the macro has been created, and then the contents of + + -q: quiet macro definition. By default, a tag line is printed + to indicate the macro has been created, and then the contents of the macro are printed. If this option is given, then no printout is produced once the macro is created. @@ -1287,7 +1287,7 @@ python-profiler package from non-free.""") return macro = Macro(lines) self.shell.define_macro(name, macro) - if not ( 'q' in opts) : + if not ( 'q' in opts) : print('Macro `%s` created. To execute, type its name (without quotes).' % name) print('=== Macro contents: ===') print(macro, end=' ') @@ -1333,7 +1333,7 @@ def parse_breakpoint(text, current_file): return current_file, int(text) else: return text[:colon], int(text[colon+1:]) - + def _format_time(timespan, precision=3): """Formats the timespan in a human readable form""" @@ -1352,13 +1352,13 @@ def _format_time(timespan, precision=3): break return " ".join(time) - + # Unfortunately the unicode 'micro' symbol can cause problems in - # certain terminals. + # certain terminals. # See bug: https://bugs.launchpad.net/ipython/+bug/348466 # Try to prevent crashes by being more secure than it needs to # E.g. eclipse is able to print a ยต, but has no sys.stdout.encoding set. - units = [u"s", u"ms",u'us',"ns"] # the save value + units = [u"s", u"ms",u'us',"ns"] # the save value if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: try: u'\xb5'.encode(sys.stdout.encoding) @@ -1366,7 +1366,7 @@ def _format_time(timespan, precision=3): except: pass scaling = [1, 1e3, 1e6, 1e9] - + if timespan > 0.0: order = min(-int(math.floor(math.log10(timespan)) // 3), 3) else: diff --git a/IPython/core/tests/test_interactiveshell.py b/IPython/core/tests/test_interactiveshell.py index ba92852..058f412 100644 --- a/IPython/core/tests/test_interactiveshell.py +++ b/IPython/core/tests/test_interactiveshell.py @@ -120,16 +120,16 @@ class InteractiveShellTestCase(unittest.TestCase): newlen = len(ip.user_ns['In']) self.assertEqual(oldlen+1, newlen) self.assertEqual(ip.user_ns['In'][-1],'1;') - + def test_magic_names_in_string(self): ip.run_cell('a = """\n%exit\n"""') self.assertEqual(ip.user_ns['a'], '\n%exit\n') - + def test_trailing_newline(self): """test that running !(command) does not raise a SyntaxError""" ip.run_cell('!(true)\n', False) ip.run_cell('!(true)\n\n\n', False) - + def test_gh_597(self): """Pretty-printing lists of objects with non-ascii reprs may cause problems.""" @@ -139,7 +139,7 @@ class InteractiveShellTestCase(unittest.TestCase): import IPython.core.formatters f = IPython.core.formatters.PlainTextFormatter() f([Spam(),Spam()]) - + def test_future_flags(self): """Check that future flags are used for parsing code (gh-777)""" @@ -162,7 +162,7 @@ class InteractiveShellTestCase(unittest.TestCase): finally: # Reset compiler flags so we don't mess up other tests. ip.compile.reset_compiler_flags() - + def test_can_pickle(self): "Can we pickle objects defined interactively (GH-29)" ip = get_ipython() @@ -171,9 +171,9 @@ class InteractiveShellTestCase(unittest.TestCase): " def __init__(self,x=[]):\n" " list.__init__(self,x)")) ip.run_cell("w=Mylist([1,2,3])") - + from pickle import dumps - + # We need to swap in our main module - this is only necessary # inside the test framework, because IPython puts the interactive module # in place (but the test framework undoes this). @@ -184,7 +184,7 @@ class InteractiveShellTestCase(unittest.TestCase): finally: sys.modules['__main__'] = _main self.assertTrue(isinstance(res, bytes)) - + def test_global_ns(self): "Code in functions must be able to access variables outside them." ip = get_ipython() @@ -234,7 +234,7 @@ class InteractiveShellTestCase(unittest.TestCase): ip.user_ns['f'] = b'Ca\xc3\xb1o' # This should not raise any exception: ip.var_expand(u'echo $f') - + def test_var_expand_local(self): """Test local variable expansion in !system and %magic calls""" # !system @@ -244,7 +244,7 @@ class InteractiveShellTestCase(unittest.TestCase): ' return ret[0]\n') res = ip.user_ns['test']() nt.assert_in('ttt', res) - + # %magic ip.run_cell('def makemacro():\n' ' macroname = "macro_var_expand_locals"\n' @@ -252,10 +252,10 @@ class InteractiveShellTestCase(unittest.TestCase): ip.user_ns['codestr'] = "str(12)" ip.run_cell('makemacro()') nt.assert_in('macro_var_expand_locals', ip.user_ns) - + def test_var_expand_self(self): """Test variable expansion with the name 'self', which was failing. - + See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218 """ ip.run_cell('class cTest:\n' @@ -264,7 +264,7 @@ class InteractiveShellTestCase(unittest.TestCase): ' res = !echo Variable: {self.classvar}\n' ' return res[0]\n') nt.assert_in('see me', ip.user_ns['cTest']().test()) - + def test_bad_var_expand(self): """var_expand on invalid formats shouldn't raise""" # SyntaxError @@ -273,19 +273,19 @@ class InteractiveShellTestCase(unittest.TestCase): self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}") # ZeroDivisionError self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}") - + def test_silent_postexec(self): """run_cell(silent=True) doesn't invoke pre/post_run_cell callbacks""" 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', post_always) - + try: ip.run_cell("1", silent=True) assert pre_always.called @@ -303,29 +303,29 @@ class InteractiveShellTestCase(unittest.TestCase): ip.events.unregister('pre_execute', pre_always) ip.events.unregister('post_run_cell', post_explicit) ip.events.unregister('post_execute', post_always) - + def test_silent_noadvance(self): """run_cell(silent=True) doesn't advance execution_count""" ec = ip.execution_count # silent should force store_history=False ip.run_cell("1", store_history=True, silent=True) - + self.assertEqual(ec, ip.execution_count) # double-check that non-silent exec did what we expected # silent to avoid ip.run_cell("1", store_history=True) self.assertEqual(ec+1, ip.execution_count) - + def test_silent_nodisplayhook(self): """run_cell(silent=True) doesn't trigger displayhook""" 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) @@ -350,10 +350,10 @@ class InteractiveShellTestCase(unittest.TestCase): In [2]: print 1,; print 2 1 2 """ - + def test_ofind_line_magic(self): from IPython.core.magic import register_line_magic - + @register_line_magic def lmagic(line): "A line magic" @@ -364,10 +364,10 @@ class InteractiveShellTestCase(unittest.TestCase): namespace = 'IPython internal', obj= lmagic.__wrapped__, parent = None) nt.assert_equal(lfind, info) - + def test_ofind_cell_magic(self): from IPython.core.magic import register_cell_magic - + @register_cell_magic def cmagic(line, cell): "A cell magic" @@ -454,7 +454,7 @@ class InteractiveShellTestCase(unittest.TestCase): def my_handler(shell, etype, value, tb, tb_offset=None): called.append(etype) shell.showtraceback((etype, value, tb), tb_offset=tb_offset) - + ip.set_custom_exc((ValueError,), my_handler) try: res = ip.run_cell("raise ValueError('test')") @@ -465,7 +465,7 @@ class InteractiveShellTestCase(unittest.TestCase): finally: # Reset the custom exception hook ip.set_custom_exc((), None) - + @skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3") def test_future_environment(self): "Can we run code with & without the shell's __future__ imports?" @@ -474,7 +474,7 @@ class InteractiveShellTestCase(unittest.TestCase): self.assertEqual(ip.user_ns['a'], 0.5) ip.run_cell("b = 1/2", shell_futures=False) self.assertEqual(ip.user_ns['b'], 0) - + ip.compile.reset_compiler_flags() # This shouldn't leak to the shell's compiler ip.run_cell("from __future__ import division \nc=1/2", shell_futures=False) @@ -551,7 +551,7 @@ class ExitCodeChecks(tt.TempFileMixin): def test_exit_code_error(self): self.system('exit 1') self.assertEqual(ip.user_ns['_exit_code'], 1) - + @skipif(not hasattr(signal, 'SIGALRM')) def test_exit_code_signal(self): self.mktmp("import signal, time\n" @@ -559,7 +559,7 @@ class ExitCodeChecks(tt.TempFileMixin): "time.sleep(1)\n") self.system("%s %s" % (sys.executable, self.fname)) self.assertEqual(ip.user_ns['_exit_code'], -signal.SIGALRM) - + @onlyif_cmds_exist("csh") def test_exit_code_signal_csh(self): SHELL = os.environ.get('SHELL', None) @@ -630,26 +630,26 @@ class TestAstTransform(unittest.TestCase): def setUp(self): self.negator = Negator() ip.ast_transformers.append(self.negator) - + def tearDown(self): ip.ast_transformers.remove(self.negator) - + def test_run_cell(self): with tt.AssertPrints('-34'): ip.run_cell('print (12 + 22)') - + # A named reference to a number shouldn't be transformed. ip.user_ns['n'] = 55 with tt.AssertNotPrints('-55'): ip.run_cell('print (n)') - + def test_timeit(self): called = set() def f(x): called.add(x) ip.push({'f':f}) - - with tt.AssertPrints("average of "): + + with tt.AssertPrints("best of "): ip.run_line_magic("timeit", "-n1 f(1)") self.assertEqual(called, {-1}) called.clear() @@ -657,29 +657,29 @@ class TestAstTransform(unittest.TestCase): with tt.AssertPrints("average of "): ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)") self.assertEqual(called, {-2, -3}) - + def test_time(self): called = [] def f(x): called.append(x) ip.push({'f':f}) - + # Test with an expression with tt.AssertPrints("Wall time: "): ip.run_line_magic("time", "f(5+9)") self.assertEqual(called, [-14]) called[:] = [] - + # Test with a statement (different code path) with tt.AssertPrints("Wall time: "): ip.run_line_magic("time", "a = f(-3 + -2)") self.assertEqual(called, [5]) - + def test_macro(self): ip.push({'a':10}) # The AST transformation makes this do a+=-1 ip.define_macro("amacro", "a+=1\nprint(a)") - + with tt.AssertPrints("9"): ip.run_cell("amacro") with tt.AssertPrints("8"): @@ -697,25 +697,25 @@ class TestAstTransform2(unittest.TestCase): def setUp(self): self.intwrapper = IntegerWrapper() ip.ast_transformers.append(self.intwrapper) - + self.calls = [] def Integer(*args): self.calls.append(args) return args ip.push({"Integer": Integer}) - + def tearDown(self): ip.ast_transformers.remove(self.intwrapper) del ip.user_ns['Integer'] - + def test_run_cell(self): ip.run_cell("n = 2") self.assertEqual(self.calls, [(2,)]) - + # This shouldn't throw an error ip.run_cell("o = 2.0") self.assertEqual(ip.user_ns['o'], 2.0) - + def test_timeit(self): called = set() def f(x): @@ -740,10 +740,10 @@ class TestAstTransformError(unittest.TestCase): def test_unregistering(self): err_transformer = ErrorTransformer() ip.ast_transformers.append(err_transformer) - + with tt.AssertPrints("unregister", channel='stderr'): ip.run_cell("1 + 2") - + # This should have been removed. nt.assert_not_in(err_transformer, ip.ast_transformers) @@ -792,18 +792,18 @@ def test__IPYTHON__(): class DummyRepr(object): def __repr__(self): return "DummyRepr" - + def _repr_html_(self): return "dummy" - + def _repr_javascript_(self): return "console.log('hi');", {'key': 'value'} - + def test_user_variables(): # enable all formatters ip.display_formatter.active_types = ip.display_formatter.format_types - + ip.user_ns['dummy'] = d = DummyRepr() keys = {'dummy', 'doesnotexist'} r = ip.user_expressions({ key:key for key in keys}) @@ -818,14 +818,14 @@ def test_user_variables(): js, jsmd = d._repr_javascript_() nt.assert_equal(data.get('application/javascript'), js) nt.assert_equal(metadata.get('application/javascript'), jsmd) - + dne = r['doesnotexist'] nt.assert_equal(dne['status'], 'error') nt.assert_equal(dne['ename'], 'NameError') - + # back to text only ip.display_formatter.active_types = ['text/plain'] - + def test_user_expression(): # enable all formatters ip.display_formatter.active_types = ip.display_formatter.format_types @@ -843,14 +843,14 @@ def test_user_expression(): data = a['data'] metadata = a['metadata'] nt.assert_equal(data.get('text/plain'), '3') - + b = r['b'] nt.assert_equal(b['status'], 'error') nt.assert_equal(b['ename'], 'ZeroDivisionError') - + # back to text only ip.display_formatter.active_types = ['text/plain'] - +