[IPython-dev] cell-to-function extension

Thomas Kluyver takowl at gmail.com
Wed Feb 26 20:40:26 EST 2014

Several people have mentioned that it's awkward when you want to reuse
exploratory code written in a notebook, first by moving it into a function
for other cells in the same notebook, and then by moving it into a module
to use from other notebooks and other modules.

At lunch today, we came up with the idea of a tool to transform a cell into
a function, to address the first of those steps. Indenting and adding 'def
foo()' by hand is easy enough, but in large cells it's easy to overlook a
critical variable. So the tool scans the code in the cell, and creates
function parameters for any variables referenced before they're defined,
along with a return statement including any variables defined in the cell.
That will usually be more than you want, but deleting code is easier than
writing it.

Using the extension is as simple as putting a "%%cell2function" at the top
of cells you want to turn into a function. Please give the extension a try
and let me know whether it's useful in your workflow, and any annoyances
you find using it.

Install command:

%install_ext https://raw.github.com/takluyver/cell2function/master/cell2function.py

Github project: https://github.com/takluyver/cell2function
Example notebook:

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20140226/b198c8ad/attachment.html>

More information about the IPython-dev mailing list