From 5f3d6e0d269e999448275e3a6a621fb3ffcbc3b1 2012-10-08 23:05:26 From: MinRK Date: 2012-10-08 23:05:26 Subject: [PATCH] fix %edit foo for interactively defined variables Effectively handles cases such as: In [1]: def foo(): return 5 In [2]: %edit foo Where `%edit foo` effectively turns into `%edit 1` by parsing the `` fake filename. --- diff --git a/IPython/core/magics/code.py b/IPython/core/magics/code.py index e1f66a6..65dcac7 100644 --- a/IPython/core/magics/code.py +++ b/IPython/core/magics/code.py @@ -17,6 +17,7 @@ import inspect import io import json import os +import re import sys from urllib2 import urlopen @@ -39,6 +40,13 @@ from IPython.utils.warn import warn # Used for exception handling in magic_edit class MacroToEdit(ValueError): pass +ipython_input_pat = re.compile(r"$") + +class InteractivelyDefined(Exception): + """Exception for interactively defined variable in magic_edit""" + def __init__(self, index): + self.index = index + @magics_class class CodeMagics(Magics): @@ -301,7 +309,11 @@ class CodeMagics(Magics): # target instead data = attr break - + + m = ipython_input_pat.match(os.path.basename(filename)) + if m: + raise InteractivelyDefined(int(m.groups()[0])) + datafile = 1 if filename is None: filename = make_filename(args) @@ -491,6 +503,11 @@ class CodeMagics(Magics): except MacroToEdit as e: self._edit_macro(args, e.args[0]) return + except InteractivelyDefined as e: + print "Editing In[%i]" % e.index + args = str(e.index) + filename, lineno, is_temp = self._find_edit_target(self.shell, + args, opts, last_call) # do actual editing here print 'Editing...',