diff --git a/IPython/core/iplib.py b/IPython/core/iplib.py index 12cf9c6..ae56cfb 100644 --- a/IPython/core/iplib.py +++ b/IPython/core/iplib.py @@ -1052,6 +1052,27 @@ class InteractiveShell(Component, Magic): # Restore the default and user aliases self.alias_manager.init_aliases() + def reset_selective(self, regex=None): + """Clear selective variables from internal namespaces based on a specified regular expression. + + Parameters + ---------- + regex : string or compiled pattern, optional + A regular expression pattern that will be used in searching variable names in the users + namespaces. + """ + if regex is not None: + try: + m = re.compile(regex) + except TypeError: + raise TypeError('regex must be a string or compiled pattern') + # Search for keys in each namespace that match the given regex + # If a match is found, delete the key/value pair. + for ns in self.ns_refs_table: + for var in ns: + if m.search(var): + del ns[var] + def push(self, variables, interactive=True): """Inject a group of variables into the IPython user namespace. diff --git a/IPython/core/magic.py b/IPython/core/magic.py index 1b673f4..ae37208 100644 --- a/IPython/core/magic.py +++ b/IPython/core/magic.py @@ -1112,6 +1112,71 @@ Currently the magic system has the following functions:\n""" # execution protection self.shell.clear_main_mod_cache() + def magic_reset_selective(self, parameter_s=''): + """Resets the namespace by removing names defined by the user. + + Input/Output history are left around in case you need them. + + %reset_selective [-f] regex + + No action is taken if regex is not included + + Options + -f : force reset without asking for confirmation. + + Examples + -------- + + In [1]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 + + In [2]: who_ls + Out[2]: ['a', 'b', 'b1', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] + + In [3]: %reset_selective -f b[2-3]m + + In [4]: who_ls + Out[4]: ['a', 'b', 'b1', 'b1m', 'b2s', 'c'] + + In [5]: %reset_selective -f d + + In [6]: who_ls + Out[6]: ['a', 'b', 'b1', 'b1m', 'b2s', 'c'] + + In [7]: %reset_selective -f c + + In [8]: who_ls + Out[8]:['a', 'b', 'b1', 'b1m', 'b2s'] + + In [9]: %reset_selective -f b + + In [10]: who_ls + Out[10]: ['a'] + + """ + + opts, regex = self.parse_options(parameter_s,'f') + + if opts.has_key('f'): + ans = True + else: + ans = self.shell.ask_yes_no( + "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") + if not ans: + print 'Nothing done.' + return + user_ns = self.shell.user_ns + if not regex: + print 'No regex pattern specified. Nothing done.' + return + else: + try: + m = re.compile(regex) + except TypeError: + raise TypeError('regex must be a string or compiled pattern') + for i in self.magic_who_ls(): + if m.search(i): + del(user_ns[i]) + def magic_logstart(self,parameter_s=''): """Start logging anywhere in a session.