{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# IPython: Beyond Normal Python\n", "\n", "There are many options for development environments for Python, and I'm often asked which one I use in my own work.\n", "My answer sometimes surprises people: my preferred environment is [IPython](http://ipython.org/) plus a text editor (in my case, Emacs or Atom depending on my mood).\n", "IPython (short for *Interactive Python*) was started in 2001 by Fernando Perez as an enhanced Python interpreter, and has since grown into a project aiming to provide, in Perez's words, \"Tools for the entire life cycle of research computing.\"\n", "If Python is the engine of our data science task, you might think of IPython as the interactive control panel.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "As well as being a useful interactive interface to Python, IPython also provides a number of useful syntactic additions to the language; we'll cover the most useful of these additions here.\n", "In addition, IPython is closely tied with the [Jupyter project](http://jupyter.org), which provides a browser-based notebook that is useful for development, collaboration, sharing, and even publication of data science results.\n", "The IPython notebook is actually a special case of the broader Jupyter notebook structure, which encompasses notebooks for Julia, R, and other programming languages.\n", "As an example of the usefulness of the notebook format, look no further than the page you are reading: the entire manuscript for this book was composed as a set of IPython notebooks.\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "IPython is about using Python effectively for interactive scientific and data-intensive computing.\n", "This chapter will start by stepping through some of the IPython features that are useful to the practice of data science, focusing especially on the syntax it offers beyond the standard features of Python.\n", "Next, we will go into a bit more depth on some of the more useful \"magic commands\" that can speed-up common tasks in creating and using data science code.\n", "Finally, we will touch on some of the features of the notebook that make it useful in understanding data and sharing results." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Shell or Notebook?\n", "\n", "There are two primary means of using IPython that we'll discuss in this chapter: the IPython shell and the IPython notebook.\n", "The bulk of the material in this chapter is relevant to both, and the examples will switch between them depending on what is most convenient.\n", "In the few sections that are relevant to just one or the other, we will explicitly state that fact.\n", "Before we start, some words on how to launch the IPython shell and IPython notebook." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Launching the IPython Shell\n", "\n", "This chapter, like most of this book, is not designed to be absorbed passively.\n", "I recommend that as you read through it, you follow along and experiment with the tools and syntax we cover: the muscle-memory you build through doing this will be far more useful than the simple act of reading about it.\n", "Start by launching the IPython interpreter by typing **``ipython``** on the command-line; alternatively, if you've installed a distribution like Anaconda or EPD, there may be a launcher specific to your system (we'll discuss this more fully in [Help and Documentation in IPython](01.01-Help-And-Documentation.ipynb)).\n", "\n", "Once you do this, you should see a prompt like the following:\n", "```\n", "IPython 4.0.1 -- An enhanced Interactive Python.\n", "? -> Introduction and overview of IPython's features.\n", "%quickref -> Quick reference.\n", "help -> Python's own help system.\n", "object? -> Details about 'object', use 'object??' for extra details.\n", "In [1]:\n", "```\n", "With that, you're ready to follow along." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Launching the Jupyter Notebook\n", "\n", "The Jupyter notebook is a browser-based graphical interface to the IPython shell, and builds on it a rich set of dynamic display capabilities.\n", "As well as executing Python/IPython statements, the notebook allows the user to include formatted text, static and dynamic visualizations, mathematical equations, JavaScript widgets, and much more.\n", "Furthermore, these documents can be saved in a way that lets other people open them and execute the code on their own systems.\n", "\n", "Though the IPython notebook is viewed and edited through your web browser window, it must connect to a running Python process in order to execute code.\n", "This process (known as a \"kernel\") can be started by running the following command in your system shell:\n", "\n", "```\n", "$ jupyter notebook\n", "```\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "This command will launch a local web server that will be visible to your browser.\n", "It immediately spits out a log showing what it is doing; that log will look something like this:\n", "\n", "```\n", "$ jupyter notebook\n", "[NotebookApp] Serving notebooks from local directory: /Users/jakevdp/PythonDataScienceHandbook\n", "[NotebookApp] 0 active kernels \n", "[NotebookApp] The IPython Notebook is running at: http://localhost:8888/\n", "[NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).\n", "```\n", "\n", "Upon issuing the command, your default browser should automatically open and navigate to the listed local URL;\n", "the exact address will depend on your system.\n", "If the browser does not open automatically, you can open a window and manually open this address (*http://localhost:8888/* in this example)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Help and Documentation in IPython\n", "\n", "If you read no other section in this chapter, read this one: I find the tools discussed here to be the most transformative contributions of IPython to my daily workflow.\n", "\n", "When a technologically-minded person is asked to help a friend, family member, or colleague with a computer problem, most of the time it's less a matter of knowing the answer as much as knowing how to quickly find an unknown answer.\n", "\n", "In data science it's the same: searchable web resources such as online documentation, mailing-list threads, and StackOverflow answers contain a wealth of information, even (especially?) if it is a topic you've found yourself searching before.\n", "\n", "*Being an effective practitioner of data science is less about memorizing the tool or command you should use for every possible situation, and more about learning to effectively find the information you don't know, whether through a web search engine or another means.*" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "One of the most useful functions of IPython/Jupyter is to shorten the gap between the user and the type of documentation and search that will help them do their work effectively.\n", "\n", "While web searches still play a role in answering complicated questions, an amazing amount of information can be found through IPython alone.\n", "Some examples of the questions IPython can help answer in a few keystrokes:\n", "\n", "- How do I call this function? What arguments and options does it have?\n", "- What does the source code of this Python object look like?\n", "- What is in this package I imported? What attributes or methods does this object have?\n", "\n", "Here we'll discuss IPython's tools to quickly access this information, namely the ``?`` character to explore documentation, the ``??`` characters to explore source code, and the Tab key for auto-completion." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Accessing Documentation with ``?``\n", "\n", "The Python language and its data science ecosystem is built with the user in mind, and one big part of that is access to documentation.\n", "Every Python object contains the reference to a string, known as a *doc string*, which in most cases will contain a concise summary of the object and how to use it.\n", "Python has a built-in ``help()`` function that can access this information and prints the results.\n", "For example, to see the documentation of the built-in ``len`` function, you can do the following:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function len in module builtins:\n", "\n", "len(obj, /)\n", " Return the number of items in a container.\n", "\n" ] } ], "source": [ "help(len)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "This notation works for just about anything, including object methods:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function insert:\n", "\n", "insert(index, object, /) method of builtins.list instance\n", " Insert object before index.\n", "\n" ] } ], "source": [ "L = [1, 2, 3]\n", "help(L.insert)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "or even objects themselves, with the documentation from their type:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on list object:\n", "\n", "class list(object)\n", " | list(iterable=(), /)\n", " | \n", " | Built-in mutable sequence.\n", " | \n", " | If no argument is given, the constructor creates a new empty list.\n", " | The argument must be an iterable if specified.\n", " | \n", " | Methods defined here:\n", " | \n", " | __add__(self, value, /)\n", " | Return self+value.\n", " | \n", " | __contains__(self, key, /)\n", " | Return key in self.\n", " | \n", " | __delitem__(self, key, /)\n", " | Delete self[key].\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getitem__(...)\n", " | x.__getitem__(y) <==> x[y]\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __iadd__(self, value, /)\n", " | Implement self+=value.\n", " | \n", " | __imul__(self, value, /)\n", " | Implement self*=value.\n", " | \n", " | __init__(self, /, *args, **kwargs)\n", " | Initialize self. See help(type(self)) for accurate signature.\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __len__(self, /)\n", " | Return len(self).\n", " | \n", " | __lt__(self, value, /)\n", " | Return self\n", "Definition: square(a)\n", "Source:\n", "def square(a):\n", " \"Return the square of a\"\n", " return a ** 2\n", "```\n", "\n", "For simple functions like this, the double question-mark can give quick insight into the under-the-hood details." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "If you play with this much, you'll notice that sometimes the ``??`` suffix doesn't display any source code: this is generally because the object in question is not implemented in Python, but in C or some other compiled extension language.\n", "If this is the case, the ``??`` suffix gives the same output as the ``?`` suffix.\n", "You'll find this particularly with many of Python's built-in objects and types, for example ``len`` from above:\n", "\n", "```ipython\n", "In [9]: len??\n", "Type: builtin_function_or_method\n", "String form: \n", "Namespace: Python builtin\n", "Docstring:\n", "len(object) -> integer\n", "\n", "Return the number of items of a sequence or mapping.\n", "```\n", "\n", "Using ``?`` and/or ``??`` gives a powerful and quick interface for finding information about what any Python function or module does." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Exploring Modules with Tab-Completion\n", "\n", "IPython's other useful interface is the use of the tab key for auto-completion and exploration of the contents of objects, modules, and name-spaces.\n", "In the examples that follow, we'll use ```` to indicate when the Tab key should be pressed." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "### Tab-completion of object contents\n", "\n", "Every Python object has various attributes and methods associated with it.\n", "Like with the ``help`` function discussed before, Python has a built-in ``dir`` function that returns a list of these, but the tab-completion interface is much easier to use in practice.\n", "To see a list of all available attributes of an object, you can type the name of the object followed by a period (\"``.``\") character and the Tab key:\n", "\n", "```ipython\n", "In [10]: L.\n", "L.append L.copy L.extend L.insert L.remove L.sort \n", "L.clear L.count L.index L.pop L.reverse \n", "```\n", "\n", "To narrow-down the list, you can type the first character or several characters of the name, and the Tab key will find the matching attributes and methods:\n", "\n", "```ipython\n", "In [10]: L.c\n", "L.clear L.copy L.count \n", "\n", "In [10]: L.co\n", "L.copy L.count \n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "If there is only a single option, pressing the Tab key will complete the line for you.\n", "For example, the following will instantly be replaced with ``L.count``:\n", "\n", "```ipython\n", "In [10]: L.cou\n", "\n", "```\n", "\n", "Though Python has no strictly-enforced distinction between public/external attributes and private/internal attributes, by convention a preceding underscore is used to denote such methods.\n", "For clarity, these private methods and special methods are omitted from the list by default, but it's possible to list them by explicitly typing the underscore:\n", "\n", "```ipython\n", "In [10]: L._\n", "L.__add__ L.__gt__ L.__reduce__\n", "L.__class__ L.__hash__ L.__reduce_ex__\n", "```\n", "\n", "For brevity, we've only shown the first couple lines of the output.\n", "Most of these are Python's special double-underscore methods (often nicknamed \"dunder\" methods)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Tab completion when importing\n", "\n", "Tab completion is also useful when importing objects from packages.\n", "Here we'll use it to find all possible imports in the ``itertools`` package that start with ``co``:\n", "```\n", "In [10]: from itertools import co\n", "combinations compress\n", "combinations_with_replacement count\n", "```\n", "Similarly, you can use tab-completion to see which imports are available on your system (this will change depending on which third-party scripts and modules are visible to your Python session):\n", "```\n", "In [10]: import \n", "Display all 399 possibilities? (y or n)\n", "Crypto dis py_compile\n", "Cython distutils pyclbr\n", "... ... ...\n", "difflib pwd zmq\n", "\n", "In [10]: import h\n", "hashlib hmac http \n", "heapq html husl \n", "```\n", "(Note that for brevity, I did not print here all 399 importable packages and modules on my system.)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Beyond tab completion: wildcard matching\n", "\n", "Tab completion is useful if you know the first few characters of the object or attribute you're looking for, but is little help if you'd like to match characters at the middle or end of the word.\n", "For this use-case, IPython provides a means of wildcard matching for names using the ``*`` character.\n", "\n", "For example, we can use this to list every object in the namespace that ends with ``Warning``:\n", "\n", "```ipython\n", "In [10]: *Warning?\n", "BytesWarning RuntimeWarning\n", "DeprecationWarning SyntaxWarning\n", "FutureWarning UnicodeWarning\n", "ImportWarning UserWarning\n", "PendingDeprecationWarning Warning\n", "ResourceWarning\n", "```\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "Notice that the ``*`` character matches any string, including the empty string.\n", "\n", "Similarly, suppose we are looking for a string method that contains the word ``find`` somewhere in its name.\n", "We can search for it this way:\n", "\n", "```ipython\n", "In [10]: str.*find*?\n", "str.find\n", "str.rfind\n", "```\n", "\n", "I find this type of flexible wildcard search can be very useful for finding a particular command when getting to know a new package or reacquainting myself with a familiar one." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# IPython Magic Commands\n", "\n", "The previous two sections 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", "We'll demonstrate and discuss a few brief examples here, and come back to more focused discussion of several useful magic commands later in the chapter." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Running External Code: ``%run``\n", "As you begin developing more extensive code, you will likely find yourself working in both 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.\n", "\n", "For example, imagine you've created a ``myscript.py`` file with the following contents:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "def square(x):\n", " \"\"\"square a number\"\"\"\n", " return x ** 2\n", "\n", "for N in range(1, 4):\n", " print(N, \"squared is\", square(N))\n" ] } ], "source": [ "%%bash\n", "\n", "cat my-script.py" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "You can execute this from your IPython session as follows:\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 squared is 1\n", "2 squared is 4\n", "3 squared is 9\n" ] } ], "source": [ "%run my-script.py" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "Note also that after you've run this script, any functions defined within it are available for use in your IPython session:\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "square(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\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": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Timing Code Execution: ``%timeit``\n", "\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", "\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "277 µs ± 4.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ] } ], "source": [ "%timeit L = [n ** 2 for n in range(1000)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The benefit of ``%timeit`` is that for short commands it will automatically perform multiple runs in order to attain more robust results.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "For multi line 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" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "299 µs ± 3.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ] } ], "source": [ "%%timeit\n", "L = []\n", "for n in range(1000):\n", " L.append(n ** 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "We can immediately see that list comprehensions are about 10% faster than the equivalent ``for``-loop construction in this case." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "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 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." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Input and Output History\n", "\n", "Previously we saw that the IPython shell allows you to access previous commands with the up and down arrow keys, or equivalently the Ctrl-p/Ctrl-n shortcuts.\n", "Additionally, in both the shell and the notebook, IPython exposes several ways to obtain the output of previous commands, as well as string versions of the commands themselves.\n", "We'll explore those here." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## IPython's ``In`` and ``Out`` Objects\n", "\n", "By now I imagine you're quite familiar with the ``In [1]:``/``Out[1]:`` style prompts used by IPython.\n", "But it turns out that these are not just pretty decoration: they give a clue as to how you can access previous inputs and outputs in your current session.\n", "Imagine you start a session that looks like this:\n", "\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.9092974268256817" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import math\n", "\n", "math.sin(2)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-0.4161468365471424" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "math.cos(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We've imported the built-in ``math`` package, then computed the sine and the cosine of the number 2.\n", "These inputs and outputs are displayed in the shell with ``In``/``Out`` labels, but there's more–IPython actually creates some Python variables called ``In`` and ``Out`` that are automatically updated to reflect this history:\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['', 'help(len)', 'L = [1, 2, 3]\\nhelp(L.insert)', 'help(L)', 'def square(a):\\n \"\"\"Return the square of a.\"\"\"\\n return a ** 2', 'help(square)', \"get_ipython().run_cell_magic('bash', '', '\\\\ncat my-script.py\\\\n')\", \"get_ipython().run_line_magic('run', 'my-script.py')\", 'square(5)', \"get_ipython().run_line_magic('timeit', 'L = [n ** 2 for n in range(1000)]')\", \"get_ipython().run_cell_magic('timeit', '', 'L = []\\\\nfor n in range(1000):\\\\n L.append(n ** 2)\\\\n')\", 'import math\\n\\nmath.sin(2)', 'math.cos(2)', 'print(str(In)[:1000])']\n" ] } ], "source": [ "print(str(In)[:1000])" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{8: 25, 11: 0.9092974268256817, 12: -0.4161468365471424}\n" ] } ], "source": [ "print(str(Out)[:1000])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The ``In`` object is a list, which keeps track of the commands in order (the first item in the list is a place-holder so that ``In[1]`` can refer to the first command):\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "help(len)\n" ] } ], "source": [ "print(In[1])\n", "import math" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The ``Out`` object is not a list but a dictionary mapping input numbers to their outputs (if any):\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{8: 25, 11: 0.9092974268256817, 12: -0.4161468365471424}\n" ] } ], "source": [ "print(Out)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "Note that not all operations have outputs: for example, ``import`` statements and ``print`` statements don't affect the output.\n", "The latter may be surprising, but makes sense if you consider that ``print`` is a function that returns ``None``; for brevity, any command that returns ``None`` is not added to ``Out``.\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Where this can be useful is if you want to interact with past results.\n", "For example, let's check the sum of ``sin(2) ** 2`` and ``cos(2) ** 2`` using the previously-computed results:\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "625.1731781895681" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Out[8] ** 2 + Out[12] ** 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "The result is ``1.0`` as we'd expect from the well-known trigonometric identity.\n", "In this case, using these previous results probably is not necessary, but it can become very handy if you execute a very expensive computation and want to reuse the result!" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Underscore Shortcuts and Previous Outputs\n", "\n", "The standard Python shell contains just one simple shortcut for accessing previous output; the variable ``_`` (i.e., a single underscore) is kept updated with the previous output; this works in IPython as well:\n" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "625.1731781895681\n" ] } ], "source": [ "print(_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "But IPython takes this a bit further—you can use a double underscore to access the second-to-last output, and a triple underscore to access the third-to-last output (skipping any commands with no output):\n", "\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-0.4161468365471424\n", "0.9092974268256817\n" ] } ], "source": [ "print(__)\n", "\n", "print(___)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "IPython stops there: more than three underscores starts to get a bit hard to count, and at that point it's easier to refer to the output by line number.\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "There is one more shortcut we should mention, however–a shorthand for ``Out[X]`` is ``_X`` (i.e., a single underscore followed by the line number):\n", "\n" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{8: 25, 11: 0.9092974268256817, 12: -0.4161468365471424, 17: 625.1731781895681}" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Out" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Suppressing Output\n", "Sometimes you might wish to suppress the output of a statement (this is perhaps most common with the plotting commands that we'll explore in [Introduction to Matplotlib](04.00-Introduction-To-Matplotlib.ipynb)).\n", "Or maybe the command you're executing produces a result that you'd prefer not like to store in your output history, perhaps so that it can be deallocated when other references are removed.\n", "The easiest way to suppress the output of a command is to add a semicolon to the end omf the line:\n" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "math.sin(2) + math.cos(2);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Note that the result is computed silently, and the output is neither displayed on the screen or stored in the ``Out`` dictionary:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "14 in Out" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Related Magic Commands\n", "For accessing a batch of previous inputs at once, the ``%history`` magic command is very helpful.\n", "Here is how you can print the first four inputs:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 1: help(len)\n", " 2:\n", "L = [1, 2, 3]\n", "help(L.insert)\n", " 3: help(L)\n" ] } ], "source": [ " %history -n 1-3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "As usual, you can type ``%history?`` for more information and a description of options available.\n", "Other similar magic commands are ``%rerun`` (which will re-execute some portion of the command history) and ``%save`` (which saves some set of the command history to a file).\n", "For more information, I suggest exploring these using the ``?`` help functionality discussed in [Help and Documentation in IPython](01.01-Help-And-Documentation.ipynb)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# IPython and Shell Commands\n", "\n", "When working interactively with the standard Python interpreter, one of the frustrations is the need to switch between multiple windows to access Python tools and system command-line tools.\n", "IPython bridges this gap, and gives you a syntax for executing shell commands directly from within the IPython terminal.\n", "The magic happens with the exclamation point: anything appearing after ``!`` on a line will be executed not by the Python kernel, but by the system command-line.\n", "\n", "The following assumes you're on a Unix-like system, such as Linux or Mac OSX.\n", "Some of the examples that follow will fail on Windows, which uses a different type of shell by default (though with the 2016 announcement of native Bash shells on Windows, soon this may no longer be an issue!).\n", "If you're unfamiliar with shell commands, I'd suggest reviewing the [Shell Tutorial](http://swcarpentry.github.io/shell-novice/) put together by the always excellent Software Carpentry Foundation." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Quick Introduction to the Shell\n", "\n", "A full intro to using the shell/terminal/command-line is well beyond the scope of this chapter, but for the uninitiated we will offer a quick introduction here.\n", "The shell is a way to interact textually with your computer.\n", "Ever since the mid 1980s, when Microsoft and Apple introduced the first versions of their now ubiquitous graphical operating systems, most computer users have interacted with their operating system through familiar clicking of menus and drag-and-drop movements.\n", "But operating systems existed long before these graphical user interfaces, and were primarily controlled through sequences of text input: at the prompt, the user would type a command, and the computer would do what the user told it to.\n", "Those early prompt systems are the precursors of the shells and terminals that most active data scientists still use today." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "\n", "Someone unfamiliar with the shell might ask why you would bother with this, when many results can be accomplished by simply clicking on icons and menus.\n", "A shell user might reply with another question: why hunt icons and click menus when you can accomplish things much more easily by typing?\n", "While it might sound like a typical tech preference impasse, when moving beyond basic tasks it quickly becomes clear that the shell offers much more control of advanced tasks, though admittedly the learning curve can intimidate the average computer user.\n", "\n", "As an example, here is a sample of a Linux/OSX shell session where a user explores, creates, and modifies directories and files on their system (``osx:~ $`` is the prompt, and everything after the ``$`` sign is the typed command; text that is preceded by a ``#`` is meant just as description, rather than something you would actually type in):\n", "\n", "```bash\n", "osx:~ $ echo \"hello world\" # echo is like Python's print function\n", "hello world\n", "\n", "osx:~ $ pwd # pwd = print working directory\n", "/home/jake # this is the \"path\" that we're sitting in\n", "\n", "osx:~ $ ls # ls = list working directory contents\n", "notebooks projects \n", "\n", "osx:~ $ cd projects/ # cd = change directory\n", "\n", "osx:projects $ pwd\n", "/home/jake/projects\n", "```\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "```bash\n", "osx:projects $ ls\n", "datasci_book mpld3 myproject.txt\n", "\n", "osx:projects $ mkdir myproject # mkdir = make new directory\n", "\n", "osx:projects $ cd myproject/\n", "\n", "osx:myproject $ mv ../myproject.txt ./ # mv = move file. Here we're moving the\n", " # file myproject.txt from one directory\n", " # up (../) to the current directory (./)\n", "osx:myproject $ ls\n", "myproject.txt\n", "```\n", "\n", "Notice that all of this is just a compact way to do familiar operations (navigating a directory structure, creating a directory, moving a file, etc.) by typing commands rather than clicking icons and menus.\n", "Note that with just a few commands (``pwd``, ``ls``, ``cd``, ``mkdir``, and ``cp``) you can do many of the most common file operations.\n", "It's when you go beyond these basics that the shell approach becomes really powerful." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Shell Commands in IPython\n", "\n", "Any command that works at the command-line can be used in IPython by prefixing it with the ``!`` character.\n", "For example, the ``ls``, ``pwd``, and ``echo`` commands can be run as follows:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Makefile matplotlib.slides.html\r\n", "\u001b[34mdata\u001b[m\u001b[m mprun_demo.py\r\n", "file.dot my-script.py\r\n", "generators.ipynb my_figure.png\r\n", "generators.slides.html networkx.ipynb\r\n", "gotchas.ipynb networkx.slides.html\r\n", "gotchas.slides.html notebooks.ipynb\r\n", "grid.edgelist numpy.ipynb\r\n", "\u001b[34mimages\u001b[m\u001b[m numpy.slides.html\r\n", "introduction.ipynb pandas.ipynb\r\n", "introduction.slides.html pandas.slides.html\r\n", "jupyter-notebooks.ipynb path.png\r\n", "jupyter-notebooks.slides.html path.to.file\r\n", "marathon-data.csv requirements.txt\r\n", "matplotlib.ipynb roget_dat.txt.gz\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/Users/mn/Developer/working-copies/pythons/APAD-course/ipynbs\r\n" ] } ], "source": [ "!pwd" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "printing from the shell\r\n" ] } ], "source": [ "!echo \"printing from the shell\"" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Passing Values to and from the Shell\n", "\n", "Shell commands can not only be called from IPython, but can also be made to interact with the IPython namespace.\n", "For example, you can save the output of any shell command to a Python list using the assignment operator:\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Makefile',\n", " 'data',\n", " 'file.dot',\n", " 'generators.ipynb',\n", " 'generators.slides.html',\n", " 'gotchas.ipynb',\n", " 'gotchas.slides.html',\n", " 'grid.edgelist',\n", " 'images',\n", " 'introduction.ipynb',\n", " 'introduction.slides.html',\n", " 'jupyter-notebooks.ipynb',\n", " 'jupyter-notebooks.slides.html',\n", " 'marathon-data.csv',\n", " 'matplotlib.ipynb',\n", " 'matplotlib.slides.html',\n", " 'mprun_demo.py',\n", " 'my-script.py',\n", " 'my_figure.png',\n", " 'networkx.ipynb',\n", " 'networkx.slides.html',\n", " 'notebooks.ipynb',\n", " 'numpy.ipynb',\n", " 'numpy.slides.html',\n", " 'pandas.ipynb',\n", " 'pandas.slides.html',\n", " 'path.png',\n", " 'path.to.file',\n", " 'requirements.txt',\n", " 'roget_dat.txt.gz']" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "contents = !ls\n", "contents" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['/Users/mn/Developer/working-copies/pythons/APAD-course/ipynbs']" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "directory = !pwd\n", "directory" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Note that these results are not returned as lists, but as a special shell return type defined in IPython:\n" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "IPython.utils.text.SList" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(directory)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "This looks and acts a lot like a Python list, but has additional functionality, such as\n", "the ``grep`` and ``fields`` methods and the ``s``, ``n``, and ``p`` properties that allow you to search, filter, and display the results in convenient ways.\n", "For more information on these, you can use IPython's built-in help features." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Communication in the other direction–passing Python variables into the shell–is possible using the ``{varname}`` syntax:\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello from Python\r\n" ] } ], "source": [ "message = \"hello from Python\"\n", "!echo {message}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "The curly braces contain the variable name, which is replaced by the variable's contents in the shell command." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Errors and Debugging\n", "\n", "Code development and data analysis always require a bit of trial and error, and IPython contains tools to streamline this process.\n", "This section will briefly cover some options for controlling Python's exception reporting, followed by exploring tools for debugging errors in code." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Controlling Exceptions: ``%xmode``\n", "\n", "Most of the time when a Python script fails, it will raise an Exception.\n", "When the interpreter hits one of these exceptions, information about the cause of the error can be found in the *traceback*, which can be accessed from within Python.\n", "With the ``%xmode`` magic function, IPython allows you to control the amount of information printed when the exception is raised.\n", "Consider the following code:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "def func1(a, b):\n", " return a / b\n", "\n", "def func2(x):\n", " a = x\n", " b = x - 1\n", " return func1(a, b)\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfunc2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mfunc2\u001b[0;34m(x)\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mfunc1\u001b[0;34m(a, b)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mfunc1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mfunc2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "func2(1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Calling ``func2`` results in an error, and reading the printed trace lets us see exactly what happened.\n", "By default, this trace includes several lines showing the context of each step that led to the error.\n", "Using the ``%xmode`` magic function (short for *Exception mode*), we can change what information is printed.\n", "\n", "``%xmode`` takes a single argument, the mode, and there are three possibilities: ``Plain``, ``Context``, and ``Verbose``.\n", "The default is ``Context``, and gives output like that just shown before.\n", "``Plain`` is more compact and gives less information:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception reporting mode: Plain\n" ] } ], "source": [ "%xmode Plain" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "Traceback \u001b[0;36m(most recent call last)\u001b[0m:\n", " File \u001b[1;32m\"\"\u001b[0m, line \u001b[1;32m1\u001b[0m, in \u001b[1;35m\u001b[0m\n func2(1)\n", " File \u001b[1;32m\"\"\u001b[0m, line \u001b[1;32m7\u001b[0m, in \u001b[1;35mfunc2\u001b[0m\n return func1(a, b)\n", "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0;36m, in \u001b[0;35mfunc1\u001b[0;36m\u001b[0m\n\u001b[0;31m return a / b\u001b[0m\n", "\u001b[0;31mZeroDivisionError\u001b[0m\u001b[0;31m:\u001b[0m division by zero\n" ] } ], "source": [ "func2(1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The ``Verbose`` mode adds some extra information, including the arguments to any functions that are called:" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception reporting mode: Verbose\n" ] } ], "source": [ "%xmode Verbose" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfunc2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m \u001b[0;36mglobal\u001b[0m \u001b[0;36mfunc2\u001b[0m \u001b[0;34m= \u001b[0m\n", "\u001b[0;32m\u001b[0m in \u001b[0;36mfunc2\u001b[0;34m(x=1)\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m \u001b[0;36mglobal\u001b[0m \u001b[0;36mfunc1\u001b[0m \u001b[0;34m= \u001b[0m\u001b[0;34m\n \u001b[0m\u001b[0;36ma\u001b[0m \u001b[0;34m= 1\u001b[0m\u001b[0;34m\n \u001b[0m\u001b[0;36mb\u001b[0m \u001b[0;34m= 0\u001b[0m\n", "\u001b[0;32m\u001b[0m in \u001b[0;36mfunc1\u001b[0;34m(a=1, b=0)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mfunc1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m \u001b[0;36ma\u001b[0m \u001b[0;34m= 1\u001b[0m\u001b[0;34m\n \u001b[0m\u001b[0;36mb\u001b[0m \u001b[0;34m= 0\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mfunc2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "func2(1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "This extra information can help narrow-in on why the exception is being raised.\n", "So why not use the ``Verbose`` mode all the time?\n", "As code gets complicated, this kind of traceback can get extremely long.\n", "Depending on the context, sometimes the brevity of ``Default`` mode is easier to work with." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Debugging: When Reading Tracebacks Is Not Enough\n", "\n", "The standard Python tool for interactive debugging is ``pdb``, the Python debugger.\n", "This debugger lets the user step through the code line by line in order to see what might be causing a more difficult error.\n", "The IPython-enhanced version of this is ``ipdb``, the IPython debugger.\n", "\n", "There are many ways to launch and use both these debuggers; we won't cover them fully here.\n", "Refer to the online documentation of these two utilities to learn more.\n", "\n", "In IPython, perhaps the most convenient interface to debugging is the ``%debug`` magic command.\n", "If you call it after hitting an exception, it will automatically open an interactive debugging prompt at the point of the exception.\n", "The ``ipdb`` prompt lets you explore the current state of the stack, explore the available variables, and even run Python commands!\n", "\n", "Let's look at the most recent exception, then do some basic tasks–print the values of ``a`` and ``b``, and type ``quit`` to quit the debugging session:" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "> \u001b[0;32m\u001b[0m(2)\u001b[0;36mfunc1\u001b[0;34m()\u001b[0m\n", "\u001b[0;32m 1 \u001b[0;31m\u001b[0;32mdef\u001b[0m \u001b[0mfunc1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m----> 2 \u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 3 \u001b[0;31m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 4 \u001b[0;31m\u001b[0;32mdef\u001b[0m \u001b[0mfunc2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 5 \u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\n", "ipdb> continue\n" ] } ], "source": [ "%debug" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The interactive debugger allows much more than this, though–we can even step up and down through the stack and explore the values of variables there:" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "> \u001b[0;32m\u001b[0m(2)\u001b[0;36mfunc1\u001b[0;34m()\u001b[0m\n", "\u001b[0;32m 1 \u001b[0;31m\u001b[0;32mdef\u001b[0m \u001b[0mfunc1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m----> 2 \u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 3 \u001b[0;31m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 4 \u001b[0;31m\u001b[0;32mdef\u001b[0m \u001b[0mfunc2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 5 \u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\n", "ipdb> continue\n" ] } ], "source": [ "%debug" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This allows you to quickly find out not only what caused the error, but what function calls led up to the error.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "If you'd like the debugger to launch automatically whenever an exception is raised, you can use the ``%pdb`` magic function to turn on this automatic behavior:" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exception reporting mode: Plain\n", "Automatic pdb calling has been turned ON\n" ] }, { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "Traceback \u001b[0;36m(most recent call last)\u001b[0m:\n", " File \u001b[1;32m\"\"\u001b[0m, line \u001b[1;32m3\u001b[0m, in \u001b[1;35m\u001b[0m\n func2(1)\n", " File \u001b[1;32m\"\"\u001b[0m, line \u001b[1;32m7\u001b[0m, in \u001b[1;35mfunc2\u001b[0m\n return func1(a, b)\n", "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0;36m, in \u001b[0;35mfunc1\u001b[0;36m\u001b[0m\n\u001b[0;31m return a / b\u001b[0m\n", "\u001b[0;31mZeroDivisionError\u001b[0m\u001b[0;31m:\u001b[0m division by zero\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "> \u001b[0;32m\u001b[0m(2)\u001b[0;36mfunc1\u001b[0;34m()\u001b[0m\n", "\u001b[0;32m 1 \u001b[0;31m\u001b[0;32mdef\u001b[0m \u001b[0mfunc1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m----> 2 \u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 3 \u001b[0;31m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 4 \u001b[0;31m\u001b[0;32mdef\u001b[0m \u001b[0mfunc2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\u001b[0;32m 5 \u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0m\n", "ipdb> continue\n" ] } ], "source": [ "%xmode Plain\n", "%pdb on\n", "func2(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, if you have a script that you'd like to run from the beginning in interactive mode, you can run it with the command ``%run -d``, and use the ``next`` command to step through the lines of code interactively." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Partial list of debugging commands\n", "\n", "There are many more available commands for interactive debugging than we've listed here; the following table contains a description of some of the more common and useful ones:\n", "\n", "| Command | Description |\n", "|-----------------|-------------------------------------------------------------|\n", "| ``list`` | Show the current location in the file |\n", "| ``h(elp)`` | Show a list of commands, or find help on a specific command |\n", "| ``q(uit)`` | Quit the debugger and the program |\n", "| ``c(ontinue)`` | Quit the debugger, continue in the program |\n", "| ``n(ext)`` | Go to the next step of the program |\n", "| ```` | Repeat the previous command |\n", "| ``p(rint)`` | Print variables |\n", "| ``s(tep)`` | Step into a subroutine |\n", "| ``r(eturn)`` | Return out of a subroutine |\n", "\n", "For more information, use the ``help`` command in the debugger, or take a look at ``ipdb``'s [online documentation](https://github.com/gotcha/ipdb)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Profiling and Timing Code\n", "\n", "In the process of developing code and creating data processing pipelines, there are often trade-offs you can make between various implementations.\n", "Early in developing your algorithm, it can be counterproductive to worry about such things. As Donald Knuth famously quipped, \"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.\"\n", "\n", "But once you have your code working, it can be useful to dig into its efficiency a bit.\n", "Sometimes it's useful to check the execution time of a given command or set of commands; other times it's useful to dig into a multiline process and determine where the bottleneck lies in some complicated series of operations.\n", "IPython provides access to a wide array of functionality for this kind of timing and profiling of code.\n", "Here we'll discuss the following IPython magic commands:\n", "\n", "- ``%time``: Time the execution of a single statement\n", "- ``%timeit``: Time repeated execution of a single statement for more accuracy\n", "- ``%prun``: Run code with the profiler\n", "- ``%lprun``: Run code with the line-by-line profiler\n", "- ``%memit``: Measure the memory use of a single statement\n", "- ``%mprun``: Run code with the line-by-line memory profiler\n", "\n", "The last four commands are not bundled with IPython–you'll need to get the ``line_profiler`` and ``memory_profiler`` extensions, which we will discuss in the following sections." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Timing Code Snippets: ``%timeit`` and ``%time``\n", "\n", "We saw the ``%timeit`` line-magic and ``%%timeit`` cell-magic in the introduction to magic functions in [IPython Magic Commands](01.03-Magic-Commands.ipynb); it can be used to time the repeated execution of snippets of code:" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.11 µs ± 4.94 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n" ] } ], "source": [ "%timeit sum(range(100))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that because this operation is so fast, ``%timeit`` automatically does a large number of repetitions.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "For slower commands, ``%timeit`` will automatically adjust and perform fewer repetitions:" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "325 ms ± 5.44 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ] } ], "source": [ "%%timeit\n", "total = 0\n", "for i in range(1000):\n", " for j in range(1000):\n", " total += i * (-1) ** j" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Sometimes repeating an operation is not the best option.\n", "For example, if we have a list that we'd like to sort, we might be misled by a repeated operation.\n", "Sorting a pre-sorted list is much faster than sorting an unsorted list, so the repetition will skew the result:" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "444 µs ± 10.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ] } ], "source": [ "import random\n", "L = [random.random() for i in range(100000)]\n", "%timeit L.sort()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "For this, the ``%time`` magic function may be a better choice. It also is a good choice for longer-running commands, when short, system-related delays are unlikely to affect the result.\n", "Let's time the sorting of an unsorted and a presorted list:" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sorting an unsorted list:\n", "CPU times: user 22.1 ms, sys: 78 µs, total: 22.1 ms\n", "Wall time: 22.1 ms\n" ] } ], "source": [ "import random\n", "L = [random.random() for i in range(100000)]\n", "print(\"sorting an unsorted list:\")\n", "%time L.sort()" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sorting an already sorted list:\n", "CPU times: user 1.29 ms, sys: 1 µs, total: 1.29 ms\n", "Wall time: 1.3 ms\n" ] } ], "source": [ "print(\"sorting an already sorted list:\")\n", "%time L.sort()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice how much faster the presorted list is to sort, but notice also how much longer the timing takes with ``%time`` versus ``%timeit``, even for the presorted list!\n", "This is a result of the fact that ``%timeit`` does some clever things under the hood to prevent system calls from interfering with the timing.\n", "For example, it prevents cleanup of unused Python objects (known as *garbage collection*) which might otherwise affect the timing.\n", "For this reason, ``%timeit`` results are usually noticeably faster than ``%time`` results." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "For ``%time`` as with ``%timeit``, using the double-percent-sign cell magic syntax allows timing of multiline scripts:" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 418 ms, sys: 2.57 ms, total: 421 ms\n", "Wall time: 420 ms\n" ] } ], "source": [ "%%time\n", "total = 0\n", "for i in range(1000):\n", " for j in range(1000):\n", " total += i * (-1) ** j" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For more information on ``%time`` and ``%timeit``, as well as their available options, use the IPython help functionality (i.e., type ``%time?`` at the IPython prompt)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Profiling Full Scripts: ``%prun``\n", "\n", "A program is made of many single statements, and sometimes timing these statements in context is more important than timing them on their own.\n", "Python contains a built-in code profiler (which you can read about in the Python documentation), but IPython offers a much more convenient way to use this profiler, in the form of the magic function ``%prun``.\n", "\n", "By way of example, we'll define a simple function that does some calculations:" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "def sum_of_lists(N):\n", " total = 0\n", " for i in range(5):\n", " L = [j ^ (j >> i) for j in range(N)]\n", " total += sum(L)\n", " return total" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Now we can call ``%prun`` with a function call to see the profiled results:" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " " ] } ], "source": [ "%prun sum_of_lists(1000000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "14 function calls in 0.705 seconds\n", "\n", " Ordered by: internal time\n", "\n", " ncalls tottime percall cumtime percall filename:lineno(function)\n", " 5 0.614 0.123 0.614 0.123 :4()\n", " 5 0.043 0.009 0.043 0.009 {built-in method builtins.sum}\n", " 1 0.036 0.036 0.693 0.693 :1(sum_of_lists)\n", " 1 0.012 0.012 0.705 0.705 :1()\n", " 1 0.000 0.000 0.705 0.705 {built-in method builtins.exec}\n", " 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The result is a table that indicates, in order of total time on each function call, where the execution is spending the most time. In this case, the bulk of execution time is in the list comprehension inside ``sum_of_lists``.\n", "From here, we could start thinking about what changes we might make to improve the performance in the algorithm.\n", "\n", "For more information on ``%prun``, as well as its available options, use the IPython help functionality (i.e., type ``%prun?`` at the IPython prompt)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Line-By-Line Profiling with ``%lprun``\n", "\n", "The function-by-function profiling of ``%prun`` is useful, but sometimes it's more convenient to have a line-by-line profile report.\n", "This is not built into Python or IPython, but there is a ``line_profiler`` package available for installation that can do this.\n", "Start by using Python's packaging tool, ``pip``, to install the ``line_profiler`` package:\n", "\n", "```\n", "$ pip install line_profiler\n", "```\n", "\n", "Next, you can use IPython to load the ``line_profiler`` IPython extension, offered as part of this package:" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "%load_ext line_profiler" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Now the ``%lprun`` command will do a line-by-line profiling of any function–in this case, we need to tell it explicitly which functions we're interested in profiling:" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "%lprun -f sum_of_lists sum_of_lists(5000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "Timer unit: 1e-06 s\n", "\n", "Total time: 0.006239 s\n", "File: /home/mn/Developer/working-copies/pythons/on-python/UniFiCourseSpring2020/mprun_demo.py\n", "Function: sum_of_lists at line 1\n", "\n", "Line # Hits Time Per Hit % Time Line Contents\n", "==============================================================\n", " 1 def sum_of_lists(N):\n", " 2 1 2.0 2.0 0.0 total = 0\n", " 3 6 6.0 1.0 0.1 for i in range(5):\n", " 4 5 5869.0 1173.8 94.1 L = [j ^ (j >> i) for j in range(N)]\n", " 5 5 218.0 43.6 3.5 total += sum(L)\n", " 6 5 144.0 28.8 2.3 del L # remove reference to L\n", " 7 1 0.0 0.0 0.0 return total```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The result is a table that indicates, in order of total time on each function call, where the execution is spending the most time. In this case, the bulk of execution time is in the list comprehension inside ``sum_of_lists``.\n", "From here, we could start thinking about what changes we might make to improve the performance in the algorithm.\n", "\n", "For more information on ``%prun``, as well as its available options, use the IPython help functionality (i.e., type ``%prun?`` at the IPython prompt)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Profiling Memory Use: ``%memit`` and ``%mprun``\n", "\n", "Another aspect of profiling is the amount of memory an operation uses.\n", "This can be evaluated with another IPython extension, the ``memory_profiler``.\n", "As with the ``line_profiler``, we start by ``pip``-installing the extension:\n", "\n", "```\n", "$ pip install memory_profiler\n", "```\n", "\n", "Then we can use IPython to load the extension:" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "%load_ext memory_profiler" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The memory profiler extension contains two useful magic functions: the ``%memit`` magic (which offers a memory-measuring equivalent of ``%timeit``) and the ``%mprun`` function (which offers a memory-measuring equivalent of ``%lprun``).\n", "The ``%memit`` function can be used rather simply:" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "peak memory: 129.71 MiB, increment: 72.76 MiB\n" ] } ], "source": [ "%memit sum_of_lists(1000000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see that this function uses about 100 MB of memory." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "For a line-by-line description of memory use, we can use the ``%mprun`` magic.\n", "Unfortunately, this magic works only for functions defined in separate modules rather than the notebook itself, so we'll start by using the ``%%file`` magic to create a simple module called ``mprun_demo.py``, which contains our ``sum_of_lists`` function, with one addition that will make our memory profiling results more clear:" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting mprun_demo.py\n" ] } ], "source": [ "%%file mprun_demo.py\n", "def sum_of_lists(N):\n", " total = 0\n", " for i in range(5):\n", " L = [j ^ (j >> i) for j in range(N)]\n", " total += sum(L)\n", " del L # remove reference to L\n", " return total" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "We can now import the new version of this function and run the memory line profiler:" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "*** KeyboardInterrupt exception caught in code being profiled.\n" ] } ], "source": [ "from mprun_demo import sum_of_lists\n", "%mprun -f sum_of_lists sum_of_lists(1000000)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "```\n", "Filename: /home/mn/Developer/working-copies/pythons/on-python/UniFiCourseSpring2020/mprun_demo.py\n", "\n", "Line # Mem usage Increment Line Contents\n", "================================================\n", " 1 85.2 MiB 85.2 MiB def sum_of_lists(N):\n", " 2 85.2 MiB 0.0 MiB total = 0\n", " 3 85.2 MiB 0.0 MiB for i in range(5):\n", " 4 112.2 MiB 0.2 MiB L = [j ^ (j >> i) for j in range(N)]\n", " 5 112.2 MiB 0.0 MiB total += sum(L)\n", " 6 85.2 MiB 0.0 MiB del L # remove reference to L\n", " 7 return total```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Here the ``Increment`` column tells us how much each line affects the total memory budget: observe that when we create and delete the list ``L``, we are adding about 25 MB of memory usage.\n", "This is on top of the background memory usage from the Python interpreter itself.\n", "\n", "For more information on ``%memit`` and ``%mprun``, as well as their available options, use the IPython help functionality (i.e., type ``%memit?`` at the IPython prompt)." ] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.0" } }, "nbformat": 4, "nbformat_minor": 1 }