Save a function definition in ipython

13,244

Solution 1

You can save the contents of line 1 with %save using:

In [2]: %save func1.py 1
The following commands were written to file `func1.py`:
def func1():
    pass

Help on %save is available with:

In [2]: %save?
Type:       Magic function
...
Docstring:
Save a set of lines or a macro to a given filename.

Usage:
  %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...

You can %edit a function body with:

In [3] %edit func1
 done. Executing edited code...

After %edit-ing your function func1, you can get the following output from IPython using _:

In [4]: _
Out[4]: 'def func1():\n    print "Hello World"\n\n'

Then, you can define or re-define a %macro with the update func1 contents like this:

In [5]: %macro new_func1_macro _
Macro `new_func1_macro` created. To execute, type its name (without quotes).
=== Macro contents: ===
def func1():
    print "Hello World"

Finally, you can save the new version of func1 with %save and the new %macro like this:

In [6]: %save func1.py new_func1_macro
The following commands were written to file `func1.py`:
def func1():
    print "Hello World"

Hope that clarifies.

Solution 2

 In [1]: def a():
   ...:     print('hello')
   ...:     return

In [2]: from inspect import getsource

In [3]: %save a.py getsource(a)

The following commands were written to file `a.py`:
def a():
    print('hello')
    return
Share:
13,244
cmh
Author by

cmh

Updated on July 05, 2022

Comments

  • cmh
    cmh almost 2 years

    When using ipython I often want to save specific functions I have defined during my session, e.g.:

    In [1]: def func1():
    ...:        pass
    ...: 
    
    In [2]: %save func1.py func1
    func1 is neither a string nor a macro.
    

    Instead I have to pick out the function definition line number from enumerate(_ih), or manually copy and paste from vim if I have %edit'd the function.

    Is there a way to achieve %save func1.py func1? I feel like it should be possible as ipython has access to the definition when using %edit.

    Edit

    Line based saving doesn't work if I have at some point edited the function with %ed. I'm looking for a way to save the new function definition in this case.