{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# IPython Magic Commands" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The previous chapter showed how IPython lets you use and explore Python efficiently and interactively.\n", "Here we'll begin discussing some of the enhancements that IPython adds on top of the normal Python syntax.\n", "These are known in IPython as *magic commands*, and are prefixed by the `%` character.\n", "These magic commands are designed to succinctly solve various common problems in standard data analysis.\n", "Magic commands come in two flavors: *line magics*, which are denoted by a single `%` prefix and operate on a single line of input, and *cell magics*, which are denoted by a double `%%` prefix and operate on multiple lines of input.\n", "I'll demonstrate and discuss a few brief examples here, and come back to a more focused discussion of several useful magic commands later." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Running External Code: %run\n", "As you begin developing more extensive code, you will likely find yourself working in IPython for interactive exploration, as well as a text editor to store code that you want to reuse.\n", "Rather than running this code in a new window, it can be convenient to run it within your IPython session.\n", "This can be done with the `%run` magic command.\n", "\n", "For example, imagine you've created a *myscript.py* file with the following contents:\n", "\n", "```python\n", "# file: myscript.py\n", "\n", "def square(x):\n", " \"\"\"square a number\"\"\"\n", " return x ** 2\n", "\n", "for N in range(1, 4):\n", " print(f\"{N} squared is {square(N)}\")\n", "```\n", "\n", "You can execute this from your IPython session as follows:\n", "\n", "```ipython\n", "In [6]: %run myscript.py\n", "1 squared is 1\n", "2 squared is 4\n", "3 squared is 9\n", "```\n", "\n", "Note also that after you've run this script, any functions defined within it are available for use in your IPython session:\n", "\n", "```ipython\n", "In [7]: square(5)\n", "Out[7]: 25\n", "```\n", "\n", "There are several options to fine-tune how your code is run; you can see the documentation in the normal way, by typing **`%run?`** in the IPython interpreter." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Timing Code Execution: %timeit\n", "Another example of a useful magic function is `%timeit`, which will automatically determine the execution time of the single-line Python statement that follows it.\n", "For example, we may want to check the performance of a list comprehension:\n", "\n", "```ipython\n", "In [8]: %timeit L = [n ** 2 for n in range(1000)]\n", "430 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n", "```\n", "\n", "The benefit of `%timeit` is that for short commands it will automatically perform multiple runs in order to attain more robust results.\n", "For multiline statements, adding a second `%` sign will turn this into a cell magic that can handle multiple lines of input.\n", "For example, here's the equivalent construction with a `for` loop:\n", "\n", "```ipython\n", "In [9]: %%timeit\n", " ...: L = []\n", " ...: for n in range(1000):\n", " ...: L.append(n ** 2)\n", " ...: \n", "484 µs ± 5.67 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n", "```\n", "\n", "We can immediately see that list comprehensions are about 10% faster than the equivalent `for` loop construction in this case.\n", "We'll explore `%timeit` and other approaches to timing and profiling code in [Profiling and Timing Code](01.07-Timing-and-Profiling.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Help on Magic Functions: ?, %magic, and %lsmagic\n", "\n", "Like normal Python functions, IPython magic functions have docstrings, and this useful\n", "documentation can be accessed in the standard manner.\n", "So, for example, to read the documentation of the `%timeit` magic function, simply type this:\n", "\n", "```ipython\n", "In [10]: %timeit?\n", "```\n", "\n", "Documentation for other functions can be accessed similarly.\n", "To access a general description of available magic functions, including some examples, you can type this:\n", "\n", "```ipython\n", "In [11]: %magic\n", "```\n", "\n", "For a quick and simple list of all available magic functions, type this:\n", "\n", "```ipython\n", "In [12]: %lsmagic\n", "```\n", "\n", "Finally, I'll mention that it is quite straightforward to define your own magic functions if you wish.\n", "I won't discuss it here, but if you are interested, see the references listed in [More IPython Resources](01.08-More-IPython-Resources.ipynb)." ] } ], "metadata": { "anaconda-cloud": {}, "jupytext": { "formats": "ipynb,md" }, "kernelspec": { "display_name": "Python 3.9.6 64-bit ('3.9.6')", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" }, "vscode": { "interpreter": { "hash": "513788764cd0ec0f97313d5418a13e1ea666d16d72f976a8acadce25a5af2ffc" } } }, "nbformat": 4, "nbformat_minor": 4 }