{ "metadata": { "name": "", "signature": "sha256:8cab3af0436792a4e51bc7dd2a1f3571914e22c494780a0b38e82513faf7e122" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "a=1 # Some variables used by our later cell\n", "z=\"hi\"\n", "y=True\n", "x = 6\n", "u = 4\n", "import sys" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Install and load the cell2function extension:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%install_ext https://raw.github.com/takluyver/cell2function/master/cell2function.py" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Installed cell2function.py. To use it, type:\n", " %load_ext cell2function\n" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "%load_ext cell2function" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we put the `%%cell2function` magic at the top of the cell we want to transform:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%cell2function\n", "b=2\n", "def subfunc(c=1, d=z):\n", " e = 99\n", " print(y)\n", "a = a*2\n", "x += 1\n", "print(sys.version)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def unnamed(z, y, a, x):\n", " b=2\n", " def subfunc(c=1, d=z):\n", " e = 99\n", " print(y)\n", " a = a*2\n", " x += 1\n", " print(sys.version)\n", " return b, subfunc, a, x\n", "\n", "b, subfunc, a, x = unnamed(z, y, a, x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also give create the function with a name:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%cell2function square\n", "squared = a**2" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "def square(a):\n", " squared = a**2\n", " return squared\n", "\n", "squared = square(a)" ], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }