"<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>\n",
"\n",
"([Changelog](#changelog))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# A collection of not-so-obvious Python stuff you should know!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<hr>\n",
"I am really looking forward to your comments and suggestions to improve and \n",
"extend this little collection! Just send me a quick note \n",
"- [Python's LEGB scope resolution and the keywords `global` and `nonlocal`](#python_legb)\n",
"\n",
"- [When mutable contents of immutable tuples aren't so mutable](#immutable_tuple)\n",
"\n",
"- [List comprehensions are fast, but generators are faster!?](#list_generator)\n",
"\n",
"- [Public vs. private class methods and name mangling](#private_class)\n",
"\n",
"- [The consequences of modifying a list when looping through it](#looping_pitfall)\n",
"\n",
"- [Dynamic binding and typos in variable names](#dynamic_binding)\n",
"\n",
"- [List slicing using indexes that are \"out of range](#out_of_range_slicing)\n",
"\n",
"- [Reusing global variable names and UnboundLocalErrors](#unboundlocalerror)\n",
"\n",
"- [Creating copies of mutable objects](#copy_mutable)\n",
"\n",
"- [Key differences between Python 2 and 3](#python_differences)\n",
"\n",
"- [Function annotations - What are those `->`'s in my Python code?](#function_annotation)\n",
"\n",
"- [Abortive statements in `finally` blocks](#finally_blocks)\n",
"\n",
"- [Assigning types to variables as values](#variable_types)\n",
"\n",
"- [Only the first clause of generators is evaluated immediately](#generator_rhs)\n",
"\n",
"- [Keyword argument unpacking syntax - `*args` and `**kwargs`](#splat_op)\n",
"\n",
"- [Metaclasses - What creates a new instance of a class?](#new_instance)\n",
"\n",
"- [Else-clauses: \"conditional else\" and \"completion else\"](#else_clauses)\n",
"\n",
"- [Interning of compile-time constants vs. run-time expressions](#string_interning)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a name='c3_class_res'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The C3 class resolution algorithm for multiple class inheritance"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we are dealing with multiple inheritance, according to the newer C3 class resolution algorithm, the following applies: \n",
"Assuming that child class C inherits from two parent classes A and B, \"class A should be checked before class B\".\n",
"\n",
"If you want to learn more, please read the [original blog](http://python-history.blogspot.ru/2010/06/method-resolution-order.html) post by Guido van Rossum.\n",
"Here, class `D` searches in `B` first, which in turn inherits from `A` (note that class `C` also inherits from `A`, but has its own `.foo()` method) so that we come up with the search order: `D, B, C, A`. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a name='pm_in_lists'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Assignment operators and lists - simple-add vs. add-AND operators"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python `list`s are mutable objects as we all know. So, if we are using the `+=` operator on `list`s, we extend the `list` by directly modifying the object directly. \n",
"\n",
"However, if we use the assigment via `my_list = my_list + ...`, we create a new list object, which can be demonstrated by the following code:"
"\"It often comes as a big surprise for programmers to find (sometimes by way of a hard-to-reproduce bug) that, unlike any other time value, midnight (i.e. `datetime.time(0,0,0)`) is False. A long discussion on the python-ideas mailing list shows that, while surprising, that behavior is desirable—at least in some quarters.\" \n",
"## Python reuses objects for small integers - use \"==\" for equality, \"is\" for identity\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This oddity occurs, because Python keeps an array of small integer objects (i.e., integers between -5 and 256, [see the doc](https://docs.python.org/2/c-api/int.html#PyInt_FromLong))."
"(*I received a comment that this is in fact a CPython artefact and **must not necessarily be true** in all implementations of Python!*)\n",
"\n",
"So the take home message is: always use \"==\" for equality, \"is\" for identity!\n",
"\n",
"Here is a [nice article](http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables) explaining it by comparing \"boxes\" (C language) with \"name tags\" (Python)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This example demonstrates that this applies indeed for integers in the range in -5 to 256:"
"## Shallow vs. deep copies if list contains other structures and objects\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Shallow copy**: \n",
"If we use the assignment operator to assign one list to another list, we just create a new name reference to the original list. If we want to create a new list object, we have to make a copy of the original list. This can be done via `a_list[:]` or `a_list.copy()`."
"As we have seen above, a shallow copy works fine if we want to create a new list with contents of the original list which we want to modify independently. \n",
"\n",
"However, if we are dealing with compound objects (e.g., lists that contain other lists, [read here](https://docs.python.org/2/library/copy.html) for more information) it becomes a little trickier.\n",
"\n",
"In the case of compound objects, a shallow copy would create a new compound object, but it would just insert the references to the contained objects into the new compound object. In contrast, a deep copy would go \"deeper\" and create also new objects \n",
"for the objects found in the original compound object. \n",
"If you follow the code, the concept should become more clear:"
"## Picking `True` values from logical `and`s and `or`s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Logical `or`:** \n",
"\n",
"`a or b == a if a else b` \n",
"- If both values in `or` expressions are `True`, Python will select the first value (e.g., select `\"a\"` in `\"a\" or \"b\"`), and the second one in `and` expressions. \n",
"This is also called **short-circuiting** - we already know that the logical `or` must be `True` if the first value is `True` and therefore can omit the evaluation of the second value.\n",
"\n",
"**Logical `and`:** \n",
"\n",
"`a and b == b if a else a` \n",
"- If both values in `and` expressions are `True`, Python will select the second value, since for a logical `and`, both values must be true.\n"
"## Don't use mutable objects as default arguments for functions!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Don't use mutable objects (e.g., dictionaries, lists, sets, etc.) as default arguments for functions! You might expect that a new list is created every time when we call the function without providing an argument for the default parameter, but this is not the case: **Python will create the mutable object (default parameter) the first time the function is defined - not when it is called**, see the following code:\n",
"Be aware of what is happening when combining \"`in`\" checks with generators, since they won't evaluate from the beginning once a position is \"consumed\"."
"Chicken or egg? In the history of Python (Python 2.2 to be specific) truth values were implemented via 1 and 0 (similar to the old C). In order to avoid syntax errors in old (but perfectly working) Python code, `bool` was added as a subclass of `int` in Python 2.3.\n",
"Remember the section about the [\"consuming generators\"](consuming_generators)? This example is somewhat related, but the result might still come unexpected. \n",
"In the first example below, we call a `lambda` function in a list comprehension, and the value `i` will be dereferenced every time we call `lambda` within the scope of the list comprehension. Since the list comprehension has already been constructed and evaluated when we for-loop through the list, the closure-variable will be set to the last value 4."
"However, by using a generator expression, we can make use of its stepwise evaluation (note that the returned variable still stems from the same closure, but the value changes as we iterate over the generator)."
"And if you are really keen on using lists, there is a nifty trick that circumvents this problem as a reader nicely pointed out in the comments: We can simply pass the loop variable `i` as a default argument to the lambdas."
"## Python's LEGB scope resolution and the keywords `global` and `nonlocal`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is nothing particularly surprising about Python's LEGB scope resolution (Local -> Enclosed -> Global -> Built-in), but it is still useful to take a look at some examples!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `global` vs. `local`\n",
"\n",
"According to the LEGB rule, Python will first look for a variable in the local scope. So if we set the variable `x = 1` `local`ly in the function's scope, it won't have an effect on the `global` `x`."
"Now, let us take a look at `local` vs. `enclosed`. Here, we set the variable `x = 1` in the `outer` function and set `x = 1` in the enclosed function `inner`. Since `inner` looks in the local scope first, it won't modify `outer`'s `x`."
"However, **there are ways** to modify the mutable contents of the tuple without raising the `TypeError`, the solution is the `.extend()` method, or alternatively `.append()` (for lists):"
"**A. Jesse Jiryu Davis** has a nice explanation for this phenomenon (Original source: [http://emptysqua.re/blog/python-increment-is-weird-part-ii/](http://emptysqua.re/blog/python-increment-is-weird-part-ii/))\n",
"\n",
"If we try to extend the list via `+=` *\"then the statement executes `STORE_SUBSCR`, which calls the C function `PyObject_SetItem`, which checks if the object supports item assignment. In our case the object is a tuple, so `PyObject_SetItem` throws the `TypeError`. Mystery solved.\"*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### One more note about the `immutable` status of tuples. Tuples are famous for being immutable. However, how comes that this code works?"
"What happens \"behind\" the curtains is that the tuple is not modified, but every time a new object is generated, which will inherit the old \"name tag\":"
"## List comprehensions are fast, but generators are faster!?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\"List comprehensions are fast, but generators are faster!?\" - No, not really (or significantly, see the benchmarks below). So what's the reason to prefer one over the other?\n",
"- use lists if you want to use the plethora of list methods \n",
"- use generators when you are dealing with huge collections to avoid memory issues"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import timeit\n",
"\n",
"def plainlist(n=100000):\n",
" my_list = []\n",
" for i in range(n):\n",
" if i % 5 == 0:\n",
" my_list.append(i)\n",
" return my_list\n",
"\n",
"def listcompr(n=100000):\n",
" my_list = [i for i in range(n) if i % 5 == 0]\n",
" return my_list\n",
"\n",
"def generator(n=100000):\n",
" my_gen = (i for i in range(n) if i % 5 == 0)\n",
" return my_gen\n",
"\n",
"def generator_yield(n=100000):\n",
" for i in range(n):\n",
" if i % 5 == 0:\n",
" yield i"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### To be fair to the list, let us exhaust the generators:"
"## Public vs. private class methods and name mangling\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Who has not stumbled across this quote \"we are all consenting adults here\" in the Python community, yet? Unlike in other languages like C++ (sorry, there are many more, but that's one I am most familiar with), we can't really protect class methods from being used outside the class (i.e., by the API user). \n",
"All we can do is to indicate methods as private to make clear that they are better not used outside the class, but it is really up to the class user, since \"we are all consenting adults here\"! \n",
"So, when we want to mark a class method as private, we can put a single underscore in front of it. \n",
"If we additionally want to avoid name clashes with other classes that might use the same method names, we can prefix the name with a double-underscore to invoke the name mangling.\n",
"\n",
"This doesn't prevent the class user to access this class member though, but he has to know the trick and also knows that it his own risk...\n",
"\n",
"Let the following example illustrate what I mean:"
"**The solution** is that we are iterating through the list index by index, and if we remove one of the items in-between, we inevitably mess around with the indexing, look at the following example, and it will become clear:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 2\n",
"1 5\n",
"2 6\n",
"[4, 5]\n"
]
}
],
"source": [
"b = [2, 4, 5, 6]\n",
"for index, item in enumerate(b):\n",
" print(index, item)\n",
" if not item % 2:\n",
" b.remove(item)\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>\n",
"<a name='dynamic_binding'></a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Dynamic binding and typos in variable names\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Be careful, dynamic binding is convenient, but can also quickly become dangerous!"
"But we have to be careful if we use a variable name that occurs in the global scope, and we want to access it in the local function scope if we want to reuse this name:"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "UnboundLocalError",
"evalue": "local variable 'var' referenced before assignment",
" var = 'locally changed' # changes the gobal variable\n",
"\n",
"var = 'global'\n",
"\n",
"my_func()\n",
"print(var)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>\n",
"<a name='copy_mutable'></a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Creating copies of mutable objects\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's assume a scenario where we want to duplicate sub`list`s of values stored in another list. If we want to create independent sub`list` object, using the arithmetic multiplication operator could lead to rather unexpected (or undesired) results:"
"[[back to Python 2.x vs 3.x overview](#py23_overview)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"####- Python 2: \n",
"We have ASCII `str()` types, separate `unicode()`, but no `byte` type\n",
"####- Python 3: \n",
"Now, we finally have Unicode (utf-8) `str`ings, and 2 byte classes: `byte` and `bytearray`s"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#############\n",
"# Python 2\n",
"#############\n",
"\n",
">>> type(unicode('is like a python3 str()'))\n",
"<type 'unicode'>\n",
"\n",
">>> type(b'byte type does not exist')\n",
"<type 'str'>\n",
"\n",
">>> 'they are really' + b' the same'\n",
"'they are really the same'\n",
"\n",
">>> type(bytearray(b'bytearray oddly does exist though'))\n",
"<type 'bytearray'>\n",
"\n",
"#############\n",
"# Python 3\n",
"#############\n",
"\n",
">>> print('strings are now utf-8 \\u03BCnico\\u0394é!')\n",
"strings are now utf-8 μnicoΔé!\n",
"\n",
"\n",
">>> type(b' and we have byte types for storing data')\n",
"<class 'bytes'>\n",
"\n",
">>> type(bytearray(b'but also bytearrays for those who prefer them over strings'))\n",
"<class 'bytearray'>\n",
"\n",
">>> 'string' + b'bytes for data'\n",
"Traceback (most recent call last):s\n",
" File \"<stdin>\", line 1, in <module>\n",
"TypeError: Can't convert 'bytes' object to str implicitly"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='print'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The print statement"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to Python 2.x vs 3.x overview](#py23_overview)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Very trivial, but this change makes sense, Python 3 now only accepts `print`s with proper parentheses - just like the other function calls ..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Python 2\n",
">>> print 'Hello, World!'\n",
"Hello, World!\n",
">>> print('Hello, World!')\n",
"Hello, World!\n",
"\n",
"# Python 3\n",
">>> print('Hello, World!')\n",
"Hello, World!\n",
">>> print 'Hello, World!'\n",
" File \"<stdin>\", line 1\n",
" print 'Hello, World!'\n",
" ^\n",
"SyntaxError: invalid syntax"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And if we want to print the output of 2 consecutive print functions on the same line, you would use a comma in Python 2, and a `end=\"\"` in Python 3:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Python 2\n",
">>> print \"line 1\", ; print 'same line'\n",
"line 1 same line\n",
"\n",
"# Python 3\n",
">>> print(\"line 1\", end=\"\") ; print (\" same line\")\n",
"line 1 same line"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='integer_div'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Integer division"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to Python 2.x vs 3.x overview](#py23_overview)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a pretty dangerous thing if you are porting code, or executing Python 3 code in Python 2 since the change in integer-division behavior can often go unnoticed. \n",
"So, I still tend to use a `float(3)/2` or `3/2.0` instead of a `3/2` in my Python 3 scripts to save the Python 2 guys some trouble ... (PS: and vice versa, you can `from __future__ import division` in your Python 2 scripts)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Python 2\n",
">>> 3 / 2\n",
"1\n",
">>> 3 // 2\n",
"1\n",
">>> 3 / 2.0\n",
"1.5\n",
">>> 3 // 2.0\n",
"1.0\n",
"\n",
"# Python 3\n",
">>> 3 / 2\n",
"1.5\n",
">>> 3 // 2\n",
"1\n",
">>> 3 / 2.0\n",
"1.5\n",
">>> 3 // 2.0\n",
"1.0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='xrange'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###`xrange()` "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to Python 2.x vs 3.x overview](#py23_overview)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" \n",
"`xrange()` was pretty popular in Python 2.x if you wanted to create an iterable object. The behavior was quite similar to a generator ('lazy evaluation'), but you could iterate over it infinitely. The advantage was that it was generally faster than `range()` (e.g., in a for-loop) - not if you had to iterate over the list multiple times, since the generation happens every time from scratch! \n",
"In Python 3, the `range()` was implemented like the `xrange()` function so that a dedicated `xrange()` function does not exist anymore."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Python 2\n",
"> python -m timeit 'for i in range(1000000):' ' pass'\n",
"10 loops, best of 3: 66 msec per loop\n",
"\n",
" > python -m timeit 'for i in xrange(1000000):' ' pass'\n",
"10 loops, best of 3: 27.8 msec per loop\n",
"\n",
"# Python 3\n",
"> python3 -m timeit 'for i in range(1000000):' ' pass'\n",
"10 loops, best of 3: 51.1 msec per loop\n",
"\n",
"> python3 -m timeit 'for i in xrange(1000000):' ' pass'\n",
"Traceback (most recent call last):\n",
" File \"/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/timeit.py\", line 292, in main\n",
" x = t.timeit(number)\n",
" File \"/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/timeit.py\", line 178, in timeit\n",
" timing = self.inner(it, self.timer)\n",
" File \"<timeit-src>\", line 6, in inner\n",
" for i in xrange(1000000):\n",
"NameError: name 'xrange' is not defined"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='raising_exceptions'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Raising exceptions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to Python 2.x vs 3.x overview](#py23_overview)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Where Python 2 accepts both notations, the 'old' and the 'new' way, Python 3 chokes (and raises a `SyntaxError` in turn) if we don't enclose the exception argument in parentheses:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Python 2\n",
">>> raise IOError, \"file error\"\n",
"Traceback (most recent call last):\n",
" File \"<stdin>\", line 1, in <module>\n",
"IOError: file error\n",
">>> raise IOError(\"file error\")\n",
"Traceback (most recent call last):\n",
" File \"<stdin>\", line 1, in <module>\n",
"IOError: file error\n",
"\n",
" \n",
"# Python 3 \n",
">>> raise IOError, \"file error\"\n",
" File \"<stdin>\", line 1\n",
" raise IOError, \"file error\"\n",
" ^\n",
"SyntaxError: invalid syntax\n",
">>> raise IOError(\"file error\")\n",
"Traceback (most recent call last):\n",
" File \"<stdin>\", line 1, in <module>\n",
"OSError: file error"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='handling_exceptions'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Handling exceptions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to Python 2.x vs 3.x overview](#py23_overview)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Also the handling of exceptions has slightly changed in Python 3. Now, we have to use the `as` keyword!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Python 2\n",
">>> try:\n",
"... blabla\n",
"... except NameError, err:\n",
"... print err, '--> our error msg'\n",
"... \n",
"name 'blabla' is not defined --> our error msg\n",
"\n",
"# Python 3\n",
">>> try:\n",
"... blabla\n",
"... except NameError as err:\n",
"... print(err, '--> our error msg')\n",
"... \n",
"name 'blabla' is not defined --> our error msg"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"<a id='next_next'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The `next()` function and `.next()` method"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to Python 2.x vs 3.x overview](#py23_overview)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Where you can use both function and method in Python 2.7.5, the `next()` function is all that remain in Python 3!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Python 2\n",
">>> my_generator = (letter for letter in 'abcdefg')\n",
">>> my_generator.next()\n",
"'a'\n",
">>> next(my_generator)\n",
"'b'\n",
"\n",
"# Python 3\n",
">>> my_generator = (letter for letter in 'abcdefg')\n",
">>> next(my_generator)\n",
"'a'\n",
">>> my_generator.next()\n",
"Traceback (most recent call last):\n",
" File \"<stdin>\", line 1, in <module>\n",
"AttributeError: 'generator' object has no attribute 'next'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='loop_leak'></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### In Python 3.x for-loop variables don't leak into the global namespace anymore"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to Python 2.x vs 3.x overview](#py23_overview)]"
]
},
{
"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.\""
"You probably will never make use of them (or at least very rarely). Usually, we write good function documentations below the function as a docstring - or at least this is how I would do it (okay this case is a little bit extreme, I have to admit):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def is_palindrome(a):\n",
" \"\"\"\n",
" Case-and punctuation insensitive check if a string is a palindrom.\n",
" \n",
" Keyword arguments:\n",
" a (str): The string to be checked if it is a palindrome.\n",
" \n",
" Returns `True` if input string is a palindrome, else False.\n",
" \n",
" \"\"\"\n",
" stripped_str = [l for l in my_str.lower() if l.isalpha()]\n",
" return stripped_str == stripped_str[::-1]\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, function annotations can be useful to indicate that work is still in progress in some cases. But they are optional and I see them very very rarely.\n",
"\n",
"As it is stated in [PEP3107](http://legacy.python.org/dev/peps/pep-3107/#fundamentals-of-function-annotations):\n",
"\n",
"1. Function annotations, both for parameters and return values, are completely optional.\n",
"\n",
"2. Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The nice thing about function annotations is their `__annotations__` attribute, which is dictionary of all the parameters and/or the `return` value you annotated."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'y': 'insert x^2 here', 'x': 'insert x here'}"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"foo1.__annotations__"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'return': 'Hi!'}"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"foo2.__annotations__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**When are they useful?**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Function annotations can be useful for a couple of things \n",
"Python's `try-except-finally` blocks are very handy for catching and handling errors. The `finally` block is always executed whether an `exception` has been raised or not as illustrated in the following example."
"Here, the abortive `return` statement in the `finally` block simply overrules the `return` in the `try` block, since **`finally` is guaranteed to always be executed.** So, be careful using abortive statements in `finally` blocks!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br>\n",
"<br>\n",
"<a name=\"variable_types\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#Assigning types to variables as values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I am not yet sure in which context this can be useful, but it is a nice fun fact to know that we can assign types as values to variables."
"# Only the first clause of generators is evaluated immediately"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The main reason why we love to use generators in certain cases (i.e., when we are dealing with large numbers of computations) is that it only computes the next value when it is needed, which is also known as \"lazy\" evaluation.\n",
"However, the first clause of an generator is already checked upon it's creation, as the following example demonstrates:"
"Certainly, this is a nice feature, since it notifies us about syntax erros immediately. However, this is (unfortunately) not the case if we have multiple cases in our generator."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"gen_succeeds = (i for i in range(5) for j in 1/0)"
"print('But obviously fails when we iterate ...')\n",
"for i in gen_succeeds:\n",
" print(i)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a name=\"splat_op\"></a>\n",
"<br>\n",
"<br>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##Keyword argument unpacking syntax - `*args` and `**kwargs`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python has a very convenient \"keyword argument unpacking syntax\" (often also referred to as \"splat\"-operators). This is particularly useful, if we want to define a function that can take a arbitrary number of input arguments."
"## Metaclasses - What creates a new instance of a class?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Usually, it is the `__init__` method when we think of instanciating a new object from a class. However, it is the static method `__new__` (it is not a class method!) that creates and returns a new instance before `__init__()` is called. \n",
"More specifically, this is what is returned: \n",
"For more information about the `__new__` method, please see the [documentation](https://www.python.org/download/releases/2.2/descrintro/#__new__).\n",
"\n",
"As a little experiment, let us screw with `__new__` so that it returns `None` and see if `__init__` will be executed:"
"As we can see in the code above, `__init__` requires the returned instance from `__new__` in order to called. So, here we just created a `NoneType` object. \n",
"Let us override the `__new__`, now and let us confirm that `__init__` is called now to instantiate the new object\":"
"## Else-clauses: \"conditional else\" and \"completion else\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I would claim that the conditional \"else\" is every programmer's daily bread and butter. However, there is a second flavor of \"else\"-clauses in Python, which I will call \"completion else\" (for reason that will become clear later). \n",
"But first, let us take a look at our \"traditional\" conditional else that we all are familiar with. \n"
"Why am I showing those simple examples? I think they are good to highlight some of the key points: It is **either** the code under the `if` clause that is executed, **or** the code under the `else` block, but not both. \n",
"If the condition of the `if` clause evaluates to `True`, the `if`-block is exectured, and if it evaluated to `False`, it is the `else` block. \n",
"\n",
"### Completion else\n",
"**In contrast** to the **either...or*** situation that we know from the conditional `else`, the completion `else` is executed if a code block finished. \n",
"To show you an example, let us use `else` for error-handling:"
"In the code above, we can see that the code under the **`else`-clause is only executed if the `try-block` was executed without encountering an error, i.e., if the `try`-block is \"complete\".** \n",
"The same rule applies to the \"completion\" `else` in while- and for-loops, which you can confirm in the following samples below."
"## Interning of compile-time constants vs. run-time expressions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[[back to top](#sections)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This might not be particularly useful, but it is nonetheless interesting: Python's interpreter is interning compile-time constants but not run-time expressions (note that this is implementation-specific).\n",
"Let us have a look at the simple example below. Here we are creating 3 variables and assign the value \"Hello\" to them in different ways before we test them for identity."
"Now, how does it come that the first expression evaluates to true, but the second does not? To answer this question, we need to take a closer look at the underlying byte codes:"