{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[Sebastian Raschka](http://www.sebastianraschka.com) \n", "\n", "- [Link to the containing GitHub Repository](https://github.com/rasbt/python_reference)\n", "- [Link to this IPython Notebook on GitHub](https://github.com/rasbt/python_reference/blob/master/tutorials/scope_resolution_legb_rule.ipynb)\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%load_ext watermark" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sebastian Raschka 01/27/2016 \n", "\n", "CPython 3.5.1\n", "IPython 4.0.3\n" ] } ], "source": [ "%watermark -a 'Sebastian Raschka' -v -d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[More information](http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/ipython_magic/watermark.ipynb) about the `watermark` magic command extension." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "I would be happy to hear your comments and suggestions. \n", "Please feel free to drop me a note via\n", "[twitter](https://twitter.com/rasbt), [email](mailto:bluewoodtree@gmail.com), or [google+](https://plus.google.com/+SebastianRaschka).\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#A beginner's guide to Python's namespaces, scope resolution, and the LEGB rule" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is a short tutorial about Python's namespaces and the scope resolution for variable names using the LEGB-rule. The following sections will provide short example code blocks that should illustrate the problem followed by short explanations. You can simply read this tutorial from start to end, but I'd like to encourage you to execute the code snippets - you can either copy & paste them, or for your convenience, simply [download this IPython notebook](https://raw.githubusercontent.com/rasbt/python_reference/master/tutorials/scope_resolution_legb_rule.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sections " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "- [Introduction to namespaces and scopes](#introduction) \n", "- [1. LG - Local and Global scopes](#section_1) \n", "- [2. LEG - Local, Enclosed, and Global scope](#section_2) \n", "- [3. LEGB - Local, Enclosed, Global, Built-in](#section_3) \n", "- [Self-assessment exercise](#assessment)\n", "- [Conclusion](#conclusion) \n", "- [Solutions](#solutions)\n", "- [Warning: For-loop variables \"leaking\" into the global namespace](#for_loop)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Objectives\n", "- Namespaces and scopes - where does Python look for variable names?\n", "- Can we define/reuse variable names for multiple objects at the same time?\n", "- In which order does Python search different namespaces for variable names?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Introduction to namespaces and scopes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Namespaces" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Roughly speaking, namespaces are just containers for mapping names to objects. As you might have already heard, everything in Python - literals, lists, dictionaries, functions, classes, etc. - is an object. \n", "Such a \"name-to-object\" mapping allows us to access an object by a name that we've assigned to it. E.g., if we make a simple string assignment via `a_string = \"Hello string\"`, we created a reference to the `\"Hello string\"` object, and henceforth we can access via its variable name `a_string`.\n", "\n", "We can picture a namespace as a Python dictionary structure, where the dictionary keys represent the names and the dictionary values the object itself (and this is also how namespaces are currently implemented in Python), e.g., \n", "\n", "
a_namespace = {'name_a':object_1, 'name_b':object_2, ...}
\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, the tricky part is that we have multiple independent namespaces in Python, and names can be reused for different namespaces (only the objects are unique, for example:\n", "\n", "
a_namespace = {'name_a':object_1, 'name_b':object_2, ...}\n",
    "b_namespace = {'name_a':object_3, 'name_b':object_4, ...}
\n", "\n", "For example, everytime we call a `for-loop` or define a function, it will create its own namespace. Namespaces also have different levels of hierarchy (the so-called \"scope\"), which we will discuss in more detail in the next section." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scope" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the section above, we have learned that namespaces can exist independently from each other and that they are structured in a certain hierarchy, which brings us to the concept of \"scope\". The \"scope\" in Python defines the \"hierarchy level\" in which we search namespaces for certain \"name-to-object\" mappings. \n", "For example, let us consider the following code:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 global\n", "5 in foo()\n" ] } ], "source": [ "i = 1\n", "\n", "def foo():\n", " i = 5\n", " print(i, 'in foo()')\n", "\n", "print(i, 'global')\n", "\n", "foo()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, we just defined the variable name `i` twice, once on the `foo` function." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- `foo_namespace = {'i':object_3, ...}` \n", "- `global_namespace = {'i':object_1, 'name_b':object_2, ...}`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, how does Python know which namespace it has to search if we want to print the value of the variable `i`? This is where Python's LEGB-rule comes into play, which we will discuss in the next section." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tip:\n", "If we want to print out the dictionary mapping of the global and local variables, we can use the\n", "the functions `global()` and `local()`" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "loc in foo(): True\n", "loc in global: False\n", "glob in global: True\n" ] } ], "source": [ "#print(globals()) # prints global namespace\n", "#print(locals()) # prints local namespace\n", "\n", "glob = 1\n", "\n", "def foo():\n", " loc = 5\n", " print('loc in foo():', 'loc' in locals())\n", "\n", "foo()\n", "print('loc in global:', 'loc' in globals()) \n", "print('glob in global:', 'foo' in globals())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scope resolution for variable names via the LEGB rule." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have seen that multiple namespaces can exist independently from each other and that they can contain the same variable names on different hierachy levels. The \"scope\" defines on which hierarchy level Python searches for a particular \"variable name\" for its associated object. Now, the next question is: \"In which order does Python search the different levels of namespaces before it finds the name-to-object' mapping?\" \n", "To answer is: It uses the LEGB-rule, which stands for\n", "\n", "**Local -> Enclosed -> Global -> Built-in**, \n", "\n", "where the arrows should denote the direction of the namespace-hierarchy search order. \n", "\n", "- *Local* can be inside a function or class method, for example. \n", "- *Enclosed* can be its `enclosing` function, e.g., if a function is wrapped inside another function. \n", "- *Global* refers to the uppermost level of the executing script itself, and \n", "- *Built-in* are special names that Python reserves for itself. \n", "\n", "So, if a particular name:object mapping cannot be found in the local namespaces, the namespaces of the enclosed scope are being searched next. If the search in the enclosed scope is unsuccessful, too, Python moves on to the global namespace, and eventually, it will search the built-in namespace (side note: if a name cannot found in any of the namespaces, a *NameError* will is raised).\n", "\n", "**Note**: \n", "Namespaces can also be further nested, for example if we import modules, or if we are defining new classes. In those cases we have to use prefixes to access those nested namespaces. Let me illustrate this concept in the following code block:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.141592653589793 from the math module\n", "3.141592653589793 from the numpy package\n", "3.141592653589793 from the scipy package\n" ] } ], "source": [ "import numpy\n", "import math\n", "import scipy\n", "\n", "print(math.pi, 'from the math module')\n", "print(numpy.pi, 'from the numpy package')\n", "print(scipy.pi, 'from the scipy package')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(This is also why we have to be careful if we import modules via \"`from a_module import *`\", since it loads the variable names into the global namespace and could potentially overwrite already existing variable names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "![LEGB figure](https://raw.githubusercontent.com/rasbt/python_reference/master/Images/scope_resolution_1.png)\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. LG - Local and Global scopes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Example 1.1** \n", "As a warm-up exercise, let us first forget about the enclosed (E) and built-in (B) scopes in the LEGB rule and only take a look at LG - the local and global scopes. \n", "What does the following code print?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a_var = 'global variable'\n", "\n", "def a_func():\n", " print(a_var, '[ a_var inside a_func() ]')\n", "\n", "a_func()\n", "print(a_var, '[ a_var outside a_func() ]')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**a)**\n", "
raises an error
\n", "\n", "**b)** \n", "
\n",
    "global value [ a_var outside a_func() ]
\n", "\n", "**c)** \n", "
global value [ a_var inside a_func() ]  \n",
    "global value [ a_var outside a_func() ]
\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[[go to solution](#solutions)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Here is why:\n", "\n", "We call `a_func()` first, which is supposed to print the value of `a_var`. According to the LEGB rule, the function will first look in its own local scope (L) if `a_var` is defined there. Since `a_func()` does not define its own `a_var`, it will look one-level above in the global scope (G) in which `a_var` has been defined previously.\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Example 1.2** \n", "Now, let us define the variable `a_var` in the global and the local scope. \n", "Can you guess what the following code will produce?" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a_var = 'global value'\n", "\n", "def a_func():\n", " a_var = 'local value'\n", " print(a_var, '[ a_var inside a_func() ]')\n", "\n", "a_func()\n", "print(a_var, '[ a_var outside a_func() ]')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**a)**\n", "
raises an error
\n", "\n", "**b)** \n", "
local value [ a_var inside a_func() ]\n",
    "global value [ a_var outside a_func() ]
\n", "\n", "**c)** \n", "
global value [ a_var inside a_func() ]  \n",
    "global value [ a_var outside a_func() ]
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[[go to solution](#solutions)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Here is why:\n", "\n", "When we call `a_func()`, it will first look in its local scope (L) for `a_var`, since `a_var` is defined in the local scope of `a_func`, its assigned value `local variable` is printed. Note that this doesn't affect the global variable, which is in a different scope." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "However, it is also possible to modify the global by, e.g., re-assigning a new value to it if we use the global keyword as the following example will illustrate:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "global value [ a_var outside a_func() ]\n", "local value [ a_var inside a_func() ]\n", "local value [ a_var outside a_func() ]\n" ] } ], "source": [ "a_var = 'global value'\n", "\n", "def a_func():\n", " global a_var\n", " a_var = 'local value'\n", " print(a_var, '[ a_var inside a_func() ]')\n", "\n", "print(a_var, '[ a_var outside a_func() ]')\n", "a_func()\n", "print(a_var, '[ a_var outside a_func() ]')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But we have to be careful about the order: it is easy to raise an `UnboundLocalError` if we don't explicitly tell Python that we want to use the global scope and try to modify a variable's value (remember, the right side of an assignment operation is executed first):" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "ename": "UnboundLocalError", "evalue": "local variable 'a_var' referenced before assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma_var\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'[ a_var outside a_func() ]'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0ma_func\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;36ma_func\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0ma_func\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----> 4\u001b[0;31m \u001b[0ma_var\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0ma_var\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma_var\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'[ a_var inside a_func() ]'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mUnboundLocalError\u001b[0m: local variable 'a_var' referenced before assignment" ] }, { "name": "stdout", "output_type": "stream", "text": [ "1 [ a_var outside a_func() ]\n" ] } ], "source": [ "a_var = 1\n", "\n", "def a_func():\n", " a_var = a_var + 1\n", " print(a_var, '[ a_var inside a_func() ]')\n", "\n", "print(a_var, '[ a_var outside a_func() ]')\n", "a_func()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. LEG - Local, Enclosed, and Global scope\n", "\n", "\n", "\n", "Now, let us introduce the concept of the enclosed (E) scope. Following the order \"Local -> Enclosed -> Global\", can you guess what the following code will print?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Example 2.1**" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a_var = 'global value'\n", "\n", "def outer():\n", " a_var = 'enclosed value'\n", " \n", " def inner():\n", " a_var = 'local value'\n", " print(a_var)\n", " \n", " inner()\n", "\n", "outer()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**a)**\n", "
global value
\n", "\n", "**b)** \n", "
enclosed value
\n", "\n", "**c)** \n", "
local value
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[[go to solution](#solutions)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Here is why:\n", "\n", "Let us quickly recapitulate what we just did: We called `outer()`, which defined the variable `a_var` locally (next to an existing `a_var` in the global scope). Next, the `outer()` function called `inner()`, which in turn defined a variable with of name `a_var` as well. The `print()` function inside `inner()` searched in the local scope first (L->E) before it went up in the scope hierarchy, and therefore it printed the value that was assigned in the local scope." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similar to the concept of the `global` keyword, which we have seen in the section above, we can use the keyword `nonlocal` inside the inner function to explicitly access a variable from the outer (enclosed) scope in order to modify its value. \n", "Note that the `nonlocal` keyword was added in Python 3.x and is not implemented in Python 2.x (yet)." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "outer before: local value\n", "in inner(): inner value\n", "outer after: inner value\n" ] } ], "source": [ "a_var = 'global value'\n", "\n", "def outer():\n", " a_var = 'local value'\n", " print('outer before:', a_var)\n", " def inner():\n", " nonlocal a_var\n", " a_var = 'inner value'\n", " print('in inner():', a_var)\n", " inner()\n", " print(\"outer after:\", a_var)\n", "outer()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. LEGB - Local, Enclosed, Global, Built-in\n", "\n", "To wrap up the LEGB rule, let us come to the built-in scope. Here, we will define our \"own\" length-funcion, which happens to bear the same name as the in-built `len()` function. What outcome do you excpect if we'd execute the following code?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Example 3**" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a_var = 'global variable'\n", "\n", "def len(in_var):\n", " print('called my len() function')\n", " l = 0\n", " for i in in_var:\n", " l += 1\n", " return l\n", "\n", "def a_func(in_var):\n", " len_in_var = len(in_var)\n", " print('Input variable is of length', len_in_var)\n", "\n", "a_func('Hello, World!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**a)**\n", "
raises an error (conflict with in-built `len()` function)
\n", "\n", "**b)** \n", "
called my len() function\n",
    "Input variable is of length 13
\n", "\n", "**c)** \n", "
Input variable is of length 13
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[[go to solution](#solutions)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Here is why:\n", "\n", "Since the exact same names can be used to map names to different objects - as long as the names are in different name spaces - there is no problem of reusing the name `len` to define our own length function (this is just for demonstration pruposes, it is NOT recommended). As we go up in Python's L -> E -> G -> B hierarchy, the function `a_func()` finds `len()` already in the global scope (G) first before it attempts to search the built-in (B) namespace." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Self-assessment exercise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, after we went through a couple of exercises, let us quickly check where we are. So, one more time: What would the following code print out?" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = 'global'\n", "\n", "def outer():\n", " \n", " def len(in_var):\n", " print('called my len() function: ', end=\"\")\n", " l = 0\n", " for i in in_var:\n", " l += 1\n", " return l\n", " \n", " a = 'local'\n", " \n", " def inner():\n", " global len\n", " nonlocal a\n", " a += ' variable'\n", " inner()\n", " print('a is', a)\n", " print(len(a))\n", "\n", "\n", "outer()\n", "\n", "print(len(a))\n", "print('a is', a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[[go to solution](#solutions)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Conclusion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I hope this short tutorial was helpful to understand the basic concept of Python's scope resolution order using the LEGB rule. I want to encourage you (as a little self-assessment exercise) to look at the code snippets again tomorrow and check if you can correctly predict all their outcomes." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### A rule of thumb" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In practice, **it is usually a bad idea to modify global variables inside the function scope**, since it often be the cause of confusion and weird errors that are hard to debug. \n", "If you want to modify a global variable via a function, it is recommended to pass it as an argument and reassign the return-value. \n", "For example:" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "a_var = 2\n", "\n", "def a_func(some_var):\n", " return 2**3\n", "\n", "a_var = a_func(a_var)\n", "print(a_var)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Solutions\n", "\n", "In order to prevent you from unintentional spoilers, I have written the solutions in binary format. In order to display the character representation, you just need to execute the following lines of code:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print('Example 1.1:', chr(int('01100011',2)))" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print('Example 1.2:', chr(int('01100010',2)))" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print('Example 2.1:', chr(int('01100011',2)))" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print('Example 3.1:', chr(int('01100010',2)))" ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Execute to run the self-assessment solution\n", "\n", "sol = \"000010100110111101110101011101000110010101110010001010\"\\\n", "\"0000101001001110100000101000001010011000010010000001101001011100110\"\\\n", "\"0100000011011000110111101100011011000010110110000100000011101100110\"\\\n", "\"0001011100100110100101100001011000100110110001100101000010100110001\"\\\n", "\"1011000010110110001101100011001010110010000100000011011010111100100\"\\\n", "\"1000000110110001100101011011100010100000101001001000000110011001110\"\\\n", "\"1010110111001100011011101000110100101101111011011100011101000100000\"\\\n", "\"0011000100110100000010100000101001100111011011000110111101100010011\"\\\n", "\"0000101101100001110100000101000001010001101100000101001100001001000\"\\\n", "\"0001101001011100110010000001100111011011000110111101100010011000010\"\\\n", "\"1101100\"\n", "\n", "sol_str =''.join(chr(int(sol[i:i+8], 2)) for i in range(0, len(sol), 8))\n", "for line in sol_str.split('\\n'):\n", " print(line)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Warning: For-loop variables \"leaking\" into the global namespace" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In contrast to some other programming languages, `for-loops` will use the scope they exist in and leave their defined loop-variable behind.\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4 -> a in for-loop\n", "4 -> a in global\n" ] } ], "source": [ "for a in range(5):\n", " if a == 4:\n", " print(a, '-> a in for-loop')\n", "print(a, '-> a in global')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**This also applies if we explicitly defined the `for-loop` variable in the global namespace before!** In this case it will rebind the existing variable:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4 -> b in for-loop\n", "4 -> b in global\n" ] } ], "source": [ "b = 1\n", "for b in range(5):\n", " if b == 4:\n", " print(b, '-> b in for-loop')\n", "print(b, '-> b in global')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, in **Python 3.x**, we can use closures to prevent the for-loop variable to cut into the global namespace. Here is an example (exectuted in Python 3.4):" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4]\n", "1 -> i in global\n" ] } ], "source": [ "i = 1\n", "print([i for i in range(5)])\n", "print(i, '-> i in global')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Why did I mention \"Python 3.x\"? Well, as it happens, the same code executed in Python 2.x would print:\n", "\n", "
\n",
    "4 -> i in global\n",
    "
"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This goes back to a change that was made in Python 3.x and is described in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) as follows:\n",
    "\n",
    "\"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.5.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}