Last Updated: August 12, 2019
·
2.567K
· loisaidasam

Using iPython's magic %edit to easily edit large inline blocks of code

Ever use iPython and write a large function inline only to discover that you made a typo somewhere? But then what if you need a newline in that block? You could just hit up to reproduce the same code and then try and hack in the missing code you wanted with "and"... eh...

No more! After realizing your mistake, type:

%edit _NN

where NN is the number of the output prompt that you'd like to edit, then use a regular text editor to fix your inline function.

Here's an example:

In [19]: def foo():

print "bar"
....:

In [20]: %edit 19
IPython will make a temporary file named: /var/folders/2b/2tts4sd7lfnf94dwg1fmnw0000gn/T/ipythonedit2VAfeC.py
Editing... done. Executing edited code...
Out[20]: 'def foo():\n print "baz"\n \n'

In [21]: foo()
baz

What I did there was define a function called foo() that printed out "bar", then decided that what I really wanted foo() to do was to print out "baz", so I edited it with vi and then saved and quit, which led to my changes being applied, as demonstrated.

Or if you don't believe me, read the docs:
http://ipython.org/ipython-doc/dev/interactive/tips.html