From e37887a2cbe1615ad702d7b0ad375024d6b16314 2012-01-25 09:46:04 From: Paul Ivanov Date: 2012-01-25 09:46:04 Subject: [PATCH] %reset now takes optional in/out/dhist/array args this functionality used to live in extensions/clearcmd.py, and in PR #1309, due to the fact that we already had a %clear magic for resetting the screen, it was decided that it'd be best to incorporate the functionality inside the %reset magic. --- diff --git a/IPython/core/completerlib.py b/IPython/core/completerlib.py index 7db6bef..466041f 100644 --- a/IPython/core/completerlib.py +++ b/IPython/core/completerlib.py @@ -316,6 +316,6 @@ def cd_completer(self, event): return [compress_user(p, tilde_expand, tilde_val) for p in found] -def clear_completer(self, event): - "A completer for %clear magic" - return 'in out array dhist'.split() +def reset_completer(self, event): + "A completer for %reset magic" + return '-f -s in out array dhist'.split() diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 14e1386..804c4a4 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -1840,7 +1840,7 @@ class InteractiveShell(SingletonConfigurable, Magic): """ from IPython.core.completer import IPCompleter from IPython.core.completerlib import (module_completer, - magic_run_completer, cd_completer, clear_completer) + magic_run_completer, cd_completer, reset_completer) self.Completer = IPCompleter(shell=self, namespace=self.user_ns, @@ -1860,7 +1860,7 @@ class InteractiveShell(SingletonConfigurable, Magic): self.set_hook('complete_command', module_completer, str_key = 'from') self.set_hook('complete_command', magic_run_completer, str_key = '%run') self.set_hook('complete_command', cd_completer, str_key = '%cd') - self.set_hook('complete_command', clear_completer, str_key = '%clear') + self.set_hook('complete_command', reset_completer, str_key = '%reset') # Only configure readline if we truly are using readline. IPython can # do tab-completion over the network, in GUIs, etc, where readline diff --git a/IPython/core/magic.py b/IPython/core/magic.py index 232c8f4..4868092 100644 --- a/IPython/core/magic.py +++ b/IPython/core/magic.py @@ -960,16 +960,31 @@ Currently the magic system has the following functions:\n""" print vstr[:25] + "<...>" + vstr[-25:] def magic_reset(self, parameter_s=''): - """Resets the namespace by removing all names defined by the user. + """Resets the namespace by removing all names defined by the user, if + called without arguments, or by removing some types of objects, such + as everything currently in IPython's In[] and Out[] containers (see + the parameters for details). Parameters ---------- - -f : force reset without asking for confirmation. + -f : force reset without asking for confirmation. + + -s : 'Soft' reset: Only clears your namespace, leaving history intact. + References to objects may be kept. By default (without this option), + we do a 'hard' reset, giving you a new session and removing all + references to objects from the current session. + + in : reset input history + + out : reset output history + + dhist : reset directory history + + array : reset only variables that are NumPy arrays - -s : 'Soft' reset: Only clears your namespace, leaving history intact. - References to objects may be kept. By default (without this option), - we do a 'hard' reset, giving you a new session and removing all - references to objects from the current session. + See Also + -------- + %reset_selective Examples -------- @@ -986,13 +1001,20 @@ Currently the magic system has the following functions:\n""" In [1]: 'a' in _ip.user_ns Out[1]: False + In [2]: %reset -f in + Flushing input history + + In [3]: %reset -f dhist in + Flushing directory history + Flushing input history + Notes ----- Calling this magic from clients that do not implement standard input, such as the ipython notebook interface, will reset the namespace without confirmation. """ - opts, args = self.parse_options(parameter_s,'sf') + opts, args = self.parse_options(parameter_s,'sf', mode='list') if 'f' in opts: ans = True else: @@ -1009,11 +1031,54 @@ Currently the magic system has the following functions:\n""" user_ns = self.shell.user_ns for i in self.magic_who_ls(): del(user_ns[i]) - - else: # Hard reset + elif len(args) == 0: # Hard reset self.shell.reset(new_session = False) + + # reset in/out/dhist/array: previously extensinions/clearcmd.py + ip = self.shell + user_ns = self.user_ns # local lookup, heavily used + + for target in args: + if target == 'out': + print "Flushing output cache (%d entries)" % len(user_ns['_oh']) + self.displayhook.flush() + + elif target == 'in': + print "Flushing input history" + pc = self.displayhook.prompt_count + 1 + for n in range(1, pc): + key = '_i'+repr(n) + user_ns.pop(key,None) + user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) + hm = ip.history_manager + # don't delete these, as %save and %macro depending on the length + # of these lists to be preserved + hm.input_hist_parsed[:] = [''] * pc + hm.input_hist_raw[:] = [''] * pc + # hm has internal machinery for _i,_ii,_iii, clear it out + hm._i = hm._ii = hm._iii = hm._i00 = u'' + + elif target == 'array': + # Support cleaning up numpy arrays + try: + from numpy import ndarray + # This must be done with items and not iteritems because we're + # going to modify the dict in-place. + for x,val in user_ns.items(): + if isinstance(val,ndarray): + del user_ns[x] + except ImportError: + print "reset array only works if Numpy is available." + + elif target == 'dhist': + print "Flushing directory history" + del user_ns['_dh'][:] + else: + print "Don't know how to reset ", + print target + ", please run `%reset?` for details" + gc.collect() def magic_reset_selective(self, parameter_s=''): """Resets the namespace by removing names defined by the user. @@ -1027,6 +1092,10 @@ Currently the magic system has the following functions:\n""" Options -f : force reset without asking for confirmation. + See Also + -------- + %reset + Examples -------- @@ -3698,60 +3767,4 @@ Defaulting color scheme to 'NoColor'""" except Exception as e: error(e) - def magic_clear(self, s): - """Clear various data (e.g. stored history data) - - %clear in - clear input history - %clear out - clear output history - %clear dhist - clear dir history - %clear array - clear only variables that are NumPy arrays - - Examples - -------- - :: - - In [1]: clear in - Flushing input history - - In [2]: clear dhist - Clearing directory history - """ - ip = self.shell - user_ns = self.user_ns # local lookup, heavily used - - for target in s.split(): - if target == 'out': - print "Flushing output cache (%d entries)" % len(user_ns['_oh']) - self.displayhook.flush() - - elif target == 'in': - print "Flushing input history" - pc = self.displayhook.prompt_count + 1 - for n in range(1, pc): - key = '_i'+repr(n) - user_ns.pop(key,None) - user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) - # don't delete these, as %save and %macro depending on the length - # of these lists to be preserved - self.history_manager.input_hist_parsed[:] = [''] * pc - self.history_manager.input_hist_raw[:] = [''] * pc - - elif target == 'array': - # Support cleaning up numpy arrays - try: - from numpy import ndarray - # This must be done with items and not iteritems because we're - # going to modify the dict in-place. - for x,val in user_ns.items(): - if isinstance(val,ndarray): - del user_ns[x] - except ImportError: - print "Clear array only works if Numpy is available." - - elif target == 'dhist': - print "Clearing directory history" - del user_ns['_dh'][:] - - gc.collect() - # end Magic diff --git a/IPython/core/tests/test_magic.py b/IPython/core/tests/test_magic.py index 6b39444..ff7e4d4 100644 --- a/IPython/core/tests/test_magic.py +++ b/IPython/core/tests/test_magic.py @@ -185,44 +185,44 @@ def test_macro_run(): @dec.skipif_not_numpy -def test_numpy_clear_array_undec(): - "Test '%clear array' functionality" +def test_numpy_reset_array_undec(): + "Test '%reset array' functionality" _ip.ex('import numpy as np') _ip.ex('a = np.empty(2)') yield (nt.assert_true, 'a' in _ip.user_ns) - _ip.magic('clear array') + _ip.magic('reset -f array') yield (nt.assert_false, 'a' in _ip.user_ns) -def test_clear(): - "Test '%clear' magic provided by IPython.extensions.clearcmd" +def test_reset_args(): + "Test '%reset' magic with args which used to be extensions.clearcmd" _ip = get_ipython() _ip.run_cell("parrot = 'dead'", store_history=True) - # test '%clear out', make an Out prompt + # test '%reset -f out', make an Out prompt _ip.run_cell("parrot", store_history=True) nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___']) - _ip.magic('clear out') + _ip.magic('reset -f out') nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___']) nt.assert_true(len(_ip.user_ns['Out']) == 0) - # test '%clear in' + # test '%reset -f in' _ip.run_cell("parrot", store_history=True) nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) - _ip.magic('%clear in') + _ip.magic('%reset -f in') nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) nt.assert_true(len(set(_ip.user_ns['In'])) == 1) - # test '%clear dhist' + # test '%reset -f dhist' _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing _ip.magic('cd') _ip.magic('cd -') nt.assert_true(len(_ip.user_ns['_dh']) > 0) - _ip.magic('clear dhist') + _ip.magic('reset -f dhist') nt.assert_true(len(_ip.user_ns['_dh']) == 0) _ip.run_cell("_dh = [d for d in tmp]") #restore # test that In length is preserved for %macro _ip.run_cell("print 'foo'") - _ip.run_cell("clear in") + _ip.run_cell("reset -f in") nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1) def test_time():