Skip to content

Commit

Permalink
%reset now takes optional in/out/dhist/array args
Browse files Browse the repository at this point in the history
this functionality used to live in extensions/clearcmd.py, and in
PR ipython#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.
  • Loading branch information
ivanov committed Jan 25, 2012
1 parent 792a93d commit 7a8ff85
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 82 deletions.
6 changes: 3 additions & 3 deletions IPython/core/completerlib.py
Expand Up @@ -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()
4 changes: 2 additions & 2 deletions IPython/core/interactiveshell.py
Expand Up @@ -1840,7 +1840,7 @@ def init_completer(self):
"""
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,
Expand All @@ -1860,7 +1860,7 @@ def init_completer(self):
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
Expand Down
143 changes: 78 additions & 65 deletions IPython/core/magic.py
Expand Up @@ -960,16 +960,31 @@ def type_name(v):
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
--------
Expand All @@ -986,13 +1001,20 @@ def magic_reset(self, parameter_s=''):
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:
Expand All @@ -1009,11 +1031,54 @@ def magic_reset(self, parameter_s=''):
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.
Expand All @@ -1027,6 +1092,10 @@ def magic_reset_selective(self, parameter_s=''):
Options
-f : force reset without asking for confirmation.
See Also
--------
%reset
Examples
--------
Expand Down Expand Up @@ -3698,60 +3767,4 @@ def magic_config(self, s):
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
24 changes: 12 additions & 12 deletions IPython/core/tests/test_magic.py
Expand Up @@ -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():
Expand Down

0 comments on commit 7a8ff85

Please sign in to comment.