mirror of
https://github.com/rasbt/python_reference.git
synced 2024-11-30 15:31:12 +00:00
623012b5c8
Fixed a type causing a code tag not to be formatted correctly, and fixed the answer of Example 1.2 to be 'b' instead of 'a' (which is the text's intent, I believe)
1149 lines
34 KiB
Plaintext
1149 lines
34 KiB
Plaintext
{
|
|
"metadata": {
|
|
"name": "",
|
|
"signature": "sha256:b33e0c5563d80d68580ea6ce62ae2703856ccde40aec8ff9fb1364ac70d70521"
|
|
},
|
|
"nbformat": 3,
|
|
"nbformat_minor": 0,
|
|
"worksheets": [
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"%load_ext watermark"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 1
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"collapsed": false,
|
|
"input": [
|
|
"%watermark -a 'Sebastian Raschka' -v -d"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"Sebastian Raschka 04/07/2014 \n",
|
|
"\n",
|
|
"CPython 3.3.5\n",
|
|
"IPython 2.1.0\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 3
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<font size=\"1.5em\">[More information](http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/ipython_magic/watermark.ipynb) about the `watermark` magic command extension.</font>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<hr>\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",
|
|
"<hr>"
|
|
]
|
|
},
|
|
{
|
|
"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": [
|
|
"<a name=\"sections\"></a>\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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": [
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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": [
|
|
"<a name=\"introduction\"></a>\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"<pre>a_namespace = {'name_a':object_1, 'name_b':object_2, ...}</pre> \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",
|
|
"<pre>a_namespace = {'name_a':object_1, 'name_b':object_2, ...}\n",
|
|
"b_namespace = {'name_a':object_3, 'name_b':object_4, ...}</pre>\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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"i = 1\n",
|
|
"\n",
|
|
"def foo():\n",
|
|
" i = 5\n",
|
|
" print(i, 'in foo()')\n",
|
|
"\n",
|
|
"print(i, 'global')\n",
|
|
"\n",
|
|
"foo()"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"1 global\n",
|
|
"5 in foo()\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 1
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"#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())"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"loc in foo(): True\n",
|
|
"loc in global: False\n",
|
|
"glob in global: True\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 11
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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')"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"3.141592653589793 from the math module\n",
|
|
"3.141592653589793 from the numpy package\n",
|
|
"3.141592653589793 from the scipy package\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 8
|
|
},
|
|
{
|
|
"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": [
|
|
"<br>\n",
|
|
"<br>\n",
|
|
"![LEGB figure](https://raw.githubusercontent.com/rasbt/python_reference/master/Images/scope_resolution_1.png)\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<a name=\"section_1\"></a>\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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() ]')"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 1
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**a)**\n",
|
|
"<pre>raises an error</pre>\n",
|
|
"\n",
|
|
"**b)** \n",
|
|
"<pre>\n",
|
|
"global value [ a_var outside a_func() ]</pre>\n",
|
|
"\n",
|
|
"**c)** \n",
|
|
"<pre>global value [ a_var in a_func() ] \n",
|
|
"global value [ a_var outside a_func() ]</pre>\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",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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() ]')"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 2
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**a)**\n",
|
|
"<pre>raises an error</pre>\n",
|
|
"\n",
|
|
"**b)** \n",
|
|
"<pre>local value [ a_var in a_func() ]\n",
|
|
"global value [ a_var outside a_func() ]</pre>\n",
|
|
"\n",
|
|
"**c)** \n",
|
|
"<pre>global value [ a_var in a_func() ] \n",
|
|
"global value [ a_var outside a_func() ]</pre>\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": [
|
|
"<br>\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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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() ]')"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"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"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 3
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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()"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"ename": "UnboundLocalError",
|
|
"evalue": "local variable 'a_var' referenced before assignment",
|
|
"output_type": "pyerr",
|
|
"traceback": [
|
|
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mUnboundLocalError\u001b[0m Traceback (most recent call last)",
|
|
"\u001b[0;32m<ipython-input-4-a6cdd0ee9a55>\u001b[0m in \u001b[0;36m<module>\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<ipython-input-4-a6cdd0ee9a55>\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"
|
|
]
|
|
},
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"1 [ a_var outside a_func() ]\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 4
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<a name=\"section_2\"></a>\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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()"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 4
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**a)**\n",
|
|
"<pre>global value</pre>\n",
|
|
"\n",
|
|
"**b)** \n",
|
|
"<pre>enclosed value</pre>\n",
|
|
"\n",
|
|
"**c)** \n",
|
|
"<pre>local value</pre>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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()"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"outer before: local value\n",
|
|
"in inner(): inner value\n",
|
|
"outer after: inner value\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 5
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<a name=\"section_3\"></a>\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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!')"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 6
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**a)**\n",
|
|
"<pre>raises an error (conflict with in-built `len()` function)</pre>\n",
|
|
"\n",
|
|
"**b)** \n",
|
|
"<pre>called my len() function\n",
|
|
"Input variable is of length 13</pre>\n",
|
|
"\n",
|
|
"**c)** \n",
|
|
"<pre>Input variable is of length 13</pre>"
|
|
]
|
|
},
|
|
{
|
|
"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 first before it attempts"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<a name =\"assessment\"></a>\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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)"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 59
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<a name=\"conclusion\"\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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)"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"8\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 42
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<a name = \"solutions\">\n",
|
|
"<br>\n",
|
|
"<br>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"print('Example 1.1:', chr(int('01100011',2)))"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 6
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"collapsed": false,
|
|
"input": [
|
|
"print('Example 1.2:', chr(int('01100010',2)))"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 7
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"collapsed": false,
|
|
"input": [
|
|
"print('Example 2.1:', chr(int('01100011',2)))"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 8
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"collapsed": false,
|
|
"input": [
|
|
"print('Example 3.1:', chr(int('01100010',2)))"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 9
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"collapsed": false,
|
|
"input": [
|
|
"# 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)"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"prompt_number": 58
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<br>\n",
|
|
"<br>\n",
|
|
"<a name=\"for_loop\"></a>"
|
|
]
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"for a in range(5):\n",
|
|
" if a == 4:\n",
|
|
" print(a, '-> a in for-loop')\n",
|
|
"print(a, '-> a in global')"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"4 -> a in for-loop\n",
|
|
"4 -> a in global\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 5
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"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')"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"4 -> b in for-loop\n",
|
|
"4 -> b in global\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 9
|
|
},
|
|
{
|
|
"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",
|
|
"collapsed": false,
|
|
"input": [
|
|
"i = 1\n",
|
|
"print([i for i in range(5)])\n",
|
|
"print(i, '-> i in global')"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"[0, 1, 2, 3, 4]\n",
|
|
"1 -> i in global\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 1
|
|
},
|
|
{
|
|
"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",
|
|
"<pre>\n",
|
|
"4 -> i in global\n",
|
|
"<pre>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"This goes back to a change that was made in Python 3.x and is described in [What\u2019s 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",
|
|
"collapsed": false,
|
|
"input": [],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": []
|
|
}
|
|
],
|
|
"metadata": {}
|
|
}
|
|
]
|
|
}
|