{ "metadata": { "celltoolbar": "Slideshow", "name": "", "signature": "sha256:de0dab34627de83f4edeaa260a08ebaffa8ccfea15eafc78bfc6c576f8ae8011" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "This notebook was put together by [Jake Vanderplas](http://www.vanderplas.com) for UW's [Astro 599](http://www.astro.washington.edu/users/vanderplas/Astr599_2014/) course. Source and license info is on [GitHub](https://github.com/jakevdp/2014_fall_ASTR599/)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%run talktools.py" ], "language": "python", "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [ { "html": [ "" ], "metadata": {}, "output_type": "display_data", "text": [ "" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Functions and Modules\n", "An important part of coding (in Python and in other modern language) is organizing code in easily re-used chunks.\n", "\n", "Python can work within both a *procedural* and an *object-oriented* style.\n", "\n", "- **Procedural** programming is using functions\n", "\n", "- **Object-oriented** programming is using classes\n", "\n", "We'll come back to classes later, and look at functions now." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Functions\n", "\n", "Function definitions in Python look like this:\n", "\n", "``` python\n", "def function_name(arg1, arg2, ...,\n", " kw1=val1, kw2=val2, ...)\n", "```\n", "\n", "*(Note that line-breaks between the parentheses are ignored)*\n", "\n", "**argX** are *arguments*, and are required\n", "\n", "**kwX** are *keyword arguments*, and are optional" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Functions\n", "\n", "The function name can be anything, as long as it:\n", "\n", "- contains only numbers, letters, and underscores\n", "- does not start with a number\n", "- is not the name of a built-in keyword (like ``print``, or ``for``)\n", "\n", "Note for IDL users: there is no difference between *functions* and *procedures*. All Python functions return a value: if no return is specified, it returns ``None``\n", " " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Some Examples\n", "\n", "#### A function with two arguments:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def addnums(x, y):\n", " return x + y" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "result = addnums(1, 2)\n", "result" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "3" ] } ], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "addnums(1, y=2)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "3" ] } ], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "addnums(\"A\", \"B\")" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 8, "text": [ "'AB'" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Note that the variable types are not declared (as we've discussed Python is a *dynamic* language)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Examples\n", "\n", "#### A function with a keyword" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def scale(x, factor=2.0):\n", " return x * factor" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 9 }, { "cell_type": "code", "collapsed": false, "input": [ "scale(4)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 10, "text": [ "8.0" ] } ], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "scale(4, 10)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 11, "text": [ "40" ] } ], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "scale(4, factor=10)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 12, "text": [ "40" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Arguments and Keyword arguments can either be specified by order or by name, but an unnamed argument cannot come after a named argument:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "scale(x=4, 10)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "SyntaxError", "evalue": "non-keyword arg after keyword arg (, line 1)", "output_type": "pyerr", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m scale(x=4, 10)\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m non-keyword arg after keyword arg\n" ] } ], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Return Values\n", "\n", "Returned values can be anything, which allows a lot of flexibility:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def build_dict(x, y):\n", " return {'x':x, 'y':y}\n", "\n", "build_dict(4, 5)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 14, "text": [ "{'y': 5, 'x': 4}" ] } ], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "def no_return_value():\n", " pass\n", "\n", "x = no_return_value()\n", "print(x)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "None\n" ] } ], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Keyword Arguments\n", "\n", "Keyword arguments can be a very handy way to grow new functionality without breaking old code.\n", "\n", "Imagine, for example, you had the ``build_dict`` function from above:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def build_dict(x, y):\n", " return {'x':x, 'y':y}\n", "\n", "build_dict(1, 2)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 18, "text": [ "{'y': 2, 'x': 1}" ] } ], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Now what if you want to change the names of the variables in the dictionary? Adding a keyword argument can allow this flexibility without breaking old code:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def build_dict(x, y, xname='x', yname='y'):\n", " return {xname:x, yname:y}\n", "\n", "build_dict(1, 2) # old call still works" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 19, "text": [ "{'y': 2, 'x': 1}" ] } ], "prompt_number": 19 }, { "cell_type": "code", "collapsed": false, "input": [ "build_dict(1, 2, xname='spam', yname='eggs')" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 20, "text": [ "{'eggs': 2, 'spam': 1}" ] } ], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "This is admittedly a silly example, but it shows how keywords can be used to add flexibility without breaking old APIs." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Variable Scope\n", "\n", "Python functions have their own local variables list:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def modify_x(x):\n", " x += 5\n", " return x" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 21 }, { "cell_type": "code", "collapsed": false, "input": [ "x = 10\n", "y = modify_x(x)\n", "\n", "print(x)\n", "print(y)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "10\n", "15\n" ] } ], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Modifying a variable in the function does not modify the variable globally... unless you use the ``global`` declaration" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def add_a(x):\n", " global a\n", " a += 1\n", " return x + a\n", "\n", "a = 10\n", "print(add_a(5))\n", "print(a)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "16\n", "11\n" ] } ], "prompt_number": 25 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Potential Gotcha: Simple vs Compound types\n", "\n", "Warning: Simple and Compound types are treated differently!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def add_one(x):\n", " x += 1\n", " \n", "x = 4\n", "add_one(x)\n", "print(x)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "4\n" ] } ], "prompt_number": 27 }, { "cell_type": "code", "collapsed": false, "input": [ "def add_element(L):\n", " L.append(4)\n", " \n", "L = [1, 2]\n", "add_element(L)\n", "print(L)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 2, 4]\n" ] } ], "prompt_number": 28 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Simple types (int, long, float, complex, string) are passed **by value.**\n", "\n", "Compound types (list, dict, set, tuple, user-defined objects) are passed **by reference.**\n", "\n", "Question to think about: why would this be?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Catch-all: \\*args and \\*\\*kwargs" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def cheeseshop(kind, *args, **kwargs):\n", " print(\"Do you have any\", kind, \"?\")\n", " print(\"I'm sorry, we're all out of\", kind)\n", " \n", " for arg in args:\n", " print(arg)\n", " \n", " print(40 * \"=\")\n", " \n", " for kw in kwargs:\n", " print(kw, \":\", kwargs[kw])" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 30 }, { "cell_type": "code", "collapsed": false, "input": [ "cheeseshop(\"Limburger\", \"It's very runny, sir.\",\n", " \"It's really very, VERY runny, sir.\",\n", " shopkeeper=\"Michael Palin\",\n", " client=\"John Cleese\",\n", " sketch=\"Cheese Shop Sketch\")" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Do you have any Limburger ?\n", "I'm sorry, we're all out of Limburger\n", "It's very runny, sir.\n", "It's really very, VERY runny, sir.\n", "========================================\n", "shopkeeper : Michael Palin\n", "sketch : Cheese Shop Sketch\n", "client : John Cleese\n" ] } ], "prompt_number": 31 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "*(example from [Python docs](http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments))*" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Documentation (\"doc strings\")\n", "\n", "Documentation is not required, but your future self (and anybody else using your code) will thank you." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def power_of_difference(x, y, p=2.0):\n", " \"\"\"Return the power of the difference of x and y\n", " \n", " Parameters\n", " ----------\n", " x, y : float\n", " the values to be differenced\n", " p : float (optional)\n", " the exponent (default = 2.0)\n", " \n", " Returns\n", " -------\n", " result: float\n", " (x - y) ** p\n", " \"\"\"\n", " diff = x - y\n", " return diff ** p\n", "\n", "power_of_difference(10.0, 5.0)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 32, "text": [ "25.0" ] } ], "prompt_number": 32 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "*(Note that this example follows the [Numpy documentation standard](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt))*\n", "\n", "With documentation specified this way, the IPython ``help`` command will be helpful!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "power_of_difference?" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 33 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Automatically building HTML documentation" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%file myfile.py\n", "\n", "def power_of_difference(x, y, p=2.0):\n", " \"\"\"Return the power of the difference of x and y\n", " \n", " Parameters\n", " ----------\n", " x, y : float\n", " the values to be differenced\n", " p : float (optional)\n", " the exponent (default = 2.0)\n", " \n", " Returns\n", " -------\n", " result: float\n", " (x - y) ** p\n", " \"\"\"\n", " diff = x - y\n", " return diff ** p" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Writing myfile.py\n" ] } ], "prompt_number": 34 }, { "cell_type": "code", "collapsed": false, "input": [ "# Pydoc is a command-line program bundled with Python\n", "!pydoc -w myfile" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "wrote myfile.html\r\n" ] } ], "prompt_number": 35 }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.display import HTML\n", "HTML(open('myfile.html').read())" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "html": [ "\n", "\n", "Python: module myfile\n", "\n", "\n", "\n", "\n", "\n", "
 
\n", " 
myfile
index
/Users/jakevdp/Opensource/2014_fall_ASTR599/notebooks/myfile.py
\n", "

\n", "

\n", "\n", "\n", "\n", " \n", "\n", "
 
\n", "Functions
       
power_of_difference(x, y, p=2.0)
Return the power of the difference of x and y
\n", " 
\n", "Parameters
\n", "----------
\n", "x, y : float
\n", "    the values to be differenced
\n", "p : float (optional)
\n", "    the exponent (default = 2.0)
\n", " 
\n", "Returns
\n", "-------
\n", "result: float
\n", "    (x - y) ** p
\n", "
\n", "" ], "metadata": {}, "output_type": "pyout", "prompt_number": 36, "text": [ "" ] } ], "prompt_number": 36 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Any remaining questions about functions?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Modules\n", "\n", "Modules are **organized units of code** which contain functions, classes, statements, and other definitions.\n", "\n", "Any file ending in ``.py`` is treated as a module (e.g. our file ``myfile.py`` above).\n", "\n", "Variables in modules have their own **scope**: using a name in one module will not affect variables of that name in another module." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%file mymodule.py\n", "# A simple demonstration module\n", "\n", "def add_numbers(x, y):\n", " \"\"\"add x and y\"\"\"\n", " return x + y\n", "\n", "def subtract_numbers(x, y):\n", " \"\"\"subtract y from x\"\"\"\n", " return x - y" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Overwriting mymodule.py\n" ] } ], "prompt_number": 44 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Modules are accessed using ``import module_name`` (with no ``.py``)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import mymodule" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 45 }, { "cell_type": "code", "collapsed": false, "input": [ "print('1 + 2 =', mymodule.add_numbers(1, 2))\n", "print('5 - 3 =', mymodule.subtract_numbers(5, 3))" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1 + 2 = 3\n", "5 - 3 = 2\n" ] } ], "prompt_number": 48 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Note that namespaces are important:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "add_numbers(1, 2)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "NameError", "evalue": "name 'add_numbers' is not defined", "output_type": "pyerr", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mNameError\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[0madd_numbers\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'add_numbers' is not defined" ] } ], "prompt_number": 49 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Several ways to import from modules" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "#### As a separate namespace:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import mymodule\n", "mymodule.add_numbers(1, 2)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 50, "text": [ "3" ] } ], "prompt_number": 50 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "#### Importing a single function or name:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from mymodule import add_numbers\n", "add_numbers(1, 2)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 51, "text": [ "3" ] } ], "prompt_number": 51 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "#### Renaming module contents" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from mymodule import add_numbers as new_name\n", "new_name(1, 2)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 53, "text": [ "3" ] } ], "prompt_number": 53 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "#### The Kitchen sink:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from mymodule import *\n", "subtract_numbers(5, 3)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 54, "text": [ "2" ] } ], "prompt_number": 54 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "This final method can be convenient, but should generally be avoided as it can cause name collisions and makes debugging difficult." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Module level code and documentation\n", "\n", "Your modules can have their own documentation, can define module-level variables, and can execute code when they load. For example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%file mymodule2.py\n", "\"\"\"\n", "Example module with some variables and startup code\n", "\"\"\"\n", "# this code runs when the module is loaded\n", "print(\"mymodule2 in the house!\")\n", "pi = 3.1415926\n", "favorite_food = \"spam, of course\"\n", "\n", "def multiply(a, b):\n", " return a * b" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Overwriting mymodule2.py\n" ] } ], "prompt_number": 57 }, { "cell_type": "code", "collapsed": false, "input": [ "import mymodule2" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "mymodule2 in the house!\n" ] } ], "prompt_number": 58 }, { "cell_type": "code", "collapsed": false, "input": [ "# import again and the initial code does not execute!\n", "import mymodule2" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 59 }, { "cell_type": "code", "collapsed": false, "input": [ "# access module-level documentation\n", "mymodule2?" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 60 }, { "cell_type": "code", "collapsed": false, "input": [ "mymodule2.multiply(2, 3)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 62, "text": [ "6" ] } ], "prompt_number": 62 }, { "cell_type": "code", "collapsed": false, "input": [ "mymodule2.pi" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 63, "text": [ "3.1415926" ] } ], "prompt_number": 63 }, { "cell_type": "code", "collapsed": false, "input": [ "# module variables can be modified\n", "mymodule2.favorite_food" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 64, "text": [ "'spam, of course'" ] } ], "prompt_number": 64 }, { "cell_type": "code", "collapsed": false, "input": [ "mymodule2.favorite_food = \"eggs. No spam.\"\n", "mymodule2.favorite_food" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 65, "text": [ "'eggs. No spam.'" ] } ], "prompt_number": 65 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## A Few Built-in Modules\n", "\n", "- ``sys``: exposes interactions with the system (environment, file I/O, etc.)\n", "- ``os``: exposes platform-specific operations (file statistics, directories, paths, etc.)\n", "- ``math``: exposes basic mathematical functions and constants" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import sys\n", "sys?" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 67 }, { "cell_type": "code", "collapsed": false, "input": [ "import sys\n", "import os\n", "\n", "print(\"You are using Python version\", sys.version)\n", "\n", "print(40 * '-')\n", "print(\"Current working directory is:\")\n", "print(os.getcwd())\n", "\n", "print(40 * '-')\n", "print(\"Files in the current directory:\")\n", "for f in os.listdir(os.getcwd()):\n", " print(f)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "You are using Python version 3.3.5 |Anaconda 1.6.1 (x86_64)| (default, Sep 2 2014, 13:57:31) \n", "[GCC 4.2.1 (Apple Inc. build 5577)]\n", "----------------------------------------\n", "Current working directory is:\n", "/Users/jakevdp/Opensource/2014_fall_ASTR599/notebooks\n", "----------------------------------------\n", "Files in the current directory:\n", ".ipynb_checkpoints\n", "00_intro.ipynb\n", "01_basic_training.ipynb\n", "02_advanced_data_structures.ipynb\n", "03_IPython_intro.ipynb\n", "04_Functions_and_modules.ipynb\n", "05_NumpyIntro.ipynb\n", "05_Trapezoid_Solution.ipynb\n", "06_Denoise_Solution.ipynb\n", "06_MatplotlibIntro.ipynb\n", "07_GitIntro.ipynb\n", "08_ScipyIntro.ipynb\n", "09_AdvancedStrings.ipynb\n", "10_AdvancedPython2.ipynb\n", "11_EfficientNumpy.ipynb\n", "12_AdvancedMatplotlib.ipynb\n", "__pycache__\n", "demo_agg_filter.py\n", "fig_code\n", "fig_moving_objects_multicolor.py\n", "images\n", "mod.py\n", "myfile.html\n", "myfile.py\n", "myfile.pyc\n", "mymodule.py\n", "mymodule2.py\n", "nth_fib.html\n", "number_game.py\n", "sankey_demo_rankine.py\n", "style.css\n", "talktools.py\n", "test.txt\n", "Untitled0.ipynb\n", "vizarray.py\n" ] } ], "prompt_number": 68 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Built-in modules are listed at\n", "[http://docs.python.org/2/py-modindex.html](http://docs.python.org/2/py-modindex.html)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Python builtin modules are awesome...\n", "\n", "\n", "\n", "(source: http://xkcd.com/353/)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# try importing antigravity..." ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "prompt_number": 69 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Making a script executable\n", "\n", "When a script or module is run directly from the command-line (i.e. not imported) a special variable called ``__name__`` is set to ``\"__main__\"``.\n", "\n", "So, in your module, if you want some part of the code to *only* run when the script is executed directly, then you can make it look like this:\n", "\n", "``` python\n", "# all module stuff\n", "\n", "# at the bottom, put this:\n", "if __name__ == '__main__':\n", " # do some things\n", " print \"I was called from the command-line!\"\n", "```\n", "\n", "Here's a longer example of this in action:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%file modfun.py\n", "\n", "\"\"\"\n", "Some functions written to demonstrate a bunch of concepts\n", "like modules, import and command-line programming\n", "\"\"\"\n", "import os\n", "import sys\n", "\n", "\n", "def getinfo(path=\".\",show_version=True):\n", " \"\"\"\n", " Purpose: make simple us of os and sys modules\n", " Input: path (default = \".\"), the directory you want to list\n", " \"\"\"\n", " if show_version:\n", " print(\"-\" * 40)\n", " print(\"You are using Python version \", sys.version)\n", " print(\"-\" * 40)\n", " \n", " print(\"Files in the directory \" + str(os.path.abspath(path)) + \":\")\n", " for f in os.listdir(path):\n", " print(\" \" + f)\n", " print(\"*\" * 40)\n", " \n", " \n", "if __name__ == \"__main__\":\n", " \"\"\"\n", " Executed only if run from the command line.\n", " call with\n", " modfun.py ...\n", " If no dirname is given then list the files in the current path\n", " \"\"\"\n", " if len(sys.argv) == 1:\n", " getinfo(\".\",show_version=True)\n", " else:\n", " for i,dir in enumerate(sys.argv[1:]):\n", " if os.path.isdir(dir):\n", " # if we have a directory then operate on it\n", " # only show the version info\n", " # if it's the first directory\n", " getinfo(dir,show_version=(i==0))\n", " else:\n", " print(\"Directory: \" + str(dir) + \" does not exist.\")" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Overwriting modfun.py\n" ] } ], "prompt_number": 74 }, { "cell_type": "code", "collapsed": false, "input": [ "# now execute from the command-line\n", "%run modfun.py" ], "language": "python", "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "----------------------------------------\n", "You are using Python version 3.3.5 |Anaconda 1.6.1 (x86_64)| (default, Sep 2 2014, 13:57:31) \n", "[GCC 4.2.1 (Apple Inc. build 5577)]\n", "----------------------------------------\n", "Files in the directory /Users/jakevdp/Opensource/2014_fall_ASTR599/notebooks:\n", " .ipynb_checkpoints\n", " 00_intro.ipynb\n", " 01_basic_training.ipynb\n", " 02_advanced_data_structures.ipynb\n", " 03_IPython_intro.ipynb\n", " 04_Functions_and_modules.ipynb\n", " 05_NumpyIntro.ipynb\n", " 05_Trapezoid_Solution.ipynb\n", " 06_Denoise_Solution.ipynb\n", " 06_MatplotlibIntro.ipynb\n", " 07_GitIntro.ipynb\n", " 08_ScipyIntro.ipynb\n", " 09_AdvancedStrings.ipynb\n", " 10_AdvancedPython2.ipynb\n", " 11_EfficientNumpy.ipynb\n", " 12_AdvancedMatplotlib.ipynb\n", " __pycache__\n", " demo_agg_filter.py\n", " fig_code\n", " fig_moving_objects_multicolor.py\n", " images\n", " mod.py\n", " modfun.py\n", " myfile.html\n", " myfile.py\n", " myfile.pyc\n", " mymodule.py\n", " mymodule2.py\n", " nth_fib.html\n", " number_game.py\n", " sankey_demo_rankine.py\n", " style.css\n", " talktools.py\n", " test.txt\n", " Untitled0.ipynb\n", " vizarray.py\n", "****************************************\n" ] } ], "prompt_number": 75 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Note some of the ``sys`` and ``os`` commands used in this script!" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Breakout Session:\n", "## Exploring Built-in Modules\n", "\n", "This breakout will give you a chance to explore some of the builtin modules offered by Python. For this session, please use your text editor to create the files. You'll have to \n", "\n", "1. Create and edit a new file called ``age.py``. Though you can do this via the ``%%file`` magic used above, here you should use your text editor.\n", "\n", " - within ``age.py``, import the ``datetime`` module\n", " - use ``datetime.datetime()`` to create a variable representing your birthday\n", " - use ``datetime.datetime.now()`` to create a variable representing the present date\n", " - subtract the two (this forms a ``datetime.timedelta()`` object) and print that variable.\n", " \n", " - Use this object to answer these questions:\n", " \n", " 1. How many days have you been alive?\n", " \n", " 2. How many hours have you been alive?\n", " \n", " 3. What will be the date 1000 days from now?\n", " \n", "2. Create and edit a new file called ``age1.py``. When run from the command-line with one argument, ``age1.py`` should print out the date in that many days from now. If run with three arguments, print the time in days since that date.\n", "\n", "```\n", "[~]$ python age1.py 1000\n", "date in 1000 days 2016-06-06 14:46:09.548831\n", "\n", "[~]$ python age1.py 1981 6 12\n", "days since then: 11779\n", "```" ] } ], "metadata": {} } ] }