a=1 # Some variables used by our later cell
z="hi"
y=True
x = 6
u = 4
import sys
Install and load the cell2function extension:
%install_ext https://raw.github.com/takluyver/cell2function/master/cell2function.py
Installed cell2function.py. To use it, type: %load_ext cell2function
%load_ext cell2function
Now we put the %%cell2function
magic at the top of the cell we want to transform:
%%cell2function
b=2
def subfunc(c=1, d=z):
e = 99
print(y)
a = a*2
x += 1
print(sys.version)
The result is a function in a new cell. Any variables needed by the cell are parameters, and any variables defined are return values. You can now cut this down.
def unnamed(z, y, a, x):
b=2
def subfunc(c=1, d=z):
e = 99
print(y)
a = a*2
x += 1
print(sys.version)
return b, subfunc, a, x
b, subfunc, a, x = unnamed(z, y, a, x)
You can also give create the function with a name:
%%cell2function square
squared = a**2
def square(a):
squared = a**2
return squared
squared = square(a)