types as variables

This commit is contained in:
rasbt 2014-04-26 17:02:24 -04:00
parent c561c92eea
commit 95227cb057
2 changed files with 174 additions and 28 deletions

View File

@ -1,7 +1,7 @@
{ {
"metadata": { "metadata": {
"name": "", "name": "",
"signature": "sha256:d8ba69c66769cf62e5201b70ed7d717913017f6f09492848ce164b50068bd2ba" "signature": "sha256:5e808c95d2003c791e04a26d378bc816b2010a59171244a18d73487060d9e029"
}, },
"nbformat": 3, "nbformat": 3,
"nbformat_minor": 0, "nbformat_minor": 0,
@ -79,7 +79,8 @@
"- [Creating copies of mutable objects](#copy_mutable)\n", "- [Creating copies of mutable objects](#copy_mutable)\n",
"- [Key differences between Python 2 and 3](#python_differences)\n", "- [Key differences between Python 2 and 3](#python_differences)\n",
"- [Function annotations - What are those `->`'s in my Python code?](#function_annotation)\n", "- [Function annotations - What are those `->`'s in my Python code?](#function_annotation)\n",
"- [Abortive statements in `finally` blocks](#finally_blocks)" "- [Abortive statements in `finally` blocks](#finally_blocks)\n",
"- [Assigning types to variables as values](#variable_types)"
] ]
}, },
{ {
@ -922,7 +923,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"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), to avoid syntax error in old (but perfectly working) code, `bool` was added as a subclass of `int` in Python 2.3.\n", "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",
"\n", "\n",
"Original source: [http://www.peterbe.com/plog/bool-is-int](http://www.peterbe.com/plog/bool-is-int)" "Original source: [http://www.peterbe.com/plog/bool-is-int](http://www.peterbe.com/plog/bool-is-int)"
] ]
@ -933,7 +934,7 @@
"input": [ "input": [
"print('isinstance(True, int):', isinstance(True, int))\n", "print('isinstance(True, int):', isinstance(True, int))\n",
"print('True + True:', True + True)\n", "print('True + True:', True + True)\n",
"print('3*True:', 3*True)\n", "print('3*True + True:', 3*True + True)\n",
"print('3*True - False:', 3*True - False)\n" "print('3*True - False:', 3*True - False)\n"
], ],
"language": "python", "language": "python",
@ -945,12 +946,12 @@
"text": [ "text": [
"isinstance(True, int): True\n", "isinstance(True, int): True\n",
"True + True: 2\n", "True + True: 2\n",
"3*True: 3\n", "3*True + True: 4\n",
"3*True - False: 3\n" "3*True - False: 3\n"
] ]
} }
], ],
"prompt_number": 16 "prompt_number": 28
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
@ -979,11 +980,11 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Remember the [\"consuming generators\"](consuming_generators)? This example is somewhat related, but the result might still come unexpected. \n", "Remember the section about the [\"consuming generators\"](consuming_generators)? This example is somewhat related, but the result might still come unexpected. \n",
"\n", "\n",
"(Original source: [http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html](http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html))\n", "(Original source: [http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html](http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html))\n",
"\n", "\n",
"In the first example below, where we call a `lambda` function in a list comprehension, the value `i` is dereferenced every time we call `lambda` within the scope of the list comprehension. Since the list is already constructed when we `for-loop` through the list, it is set to the last value 4." "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 is already constructed when we `for-loop` through the list, it will be set to the last value 4."
] ]
}, },
{ {
@ -1009,7 +1010,7 @@
] ]
} }
], ],
"prompt_number": 11 "prompt_number": 29
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
@ -1041,7 +1042,7 @@
] ]
} }
], ],
"prompt_number": 9 "prompt_number": 30
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
@ -1106,7 +1107,7 @@
] ]
} }
], ],
"prompt_number": 33 "prompt_number": 31
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
@ -1484,8 +1485,8 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Not, really (or significantly, see the benchmarks below). So what's the reason to prefer one over the other?\n", "\"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 list methods \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" "- use generators when you are dealing with huge collections to avoid memory issues"
] ]
}, },
@ -1699,7 +1700,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"It can be really dangerous to modify a list when iterating through - it is a very common pitfall that can cause unintended behavior! \n", "It can be really dangerous to modify a list when iterating through it - this is a very common pitfall that can cause unintended behavior! \n",
"Look at the following examples, and for a fun exercise: try to figure out what is going on before you skip to the solution!" "Look at the following examples, and for a fun exercise: try to figure out what is going on before you skip to the solution!"
] ]
}, },
@ -2865,6 +2866,78 @@
"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!" "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": [
"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."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a_var = str\n",
"a_var(123)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 1,
"text": [
"'123'"
]
}
],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from random import choice\n",
"\n",
"a, b, c = float, int, str\n",
"for i in range(5):\n",
" j = choice([a,b,c])(i)\n",
" print(j, type(j))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0 <class 'int'>\n",
"1 <class 'int'>\n",
"2.0 <class 'float'>\n",
"3 <class 'str'>\n",
"4 <class 'int'>\n"
]
}
],
"prompt_number": 4
},
{ {
"cell_type": "code", "cell_type": "code",
"collapsed": false, "collapsed": false,

View File

@ -1,7 +1,7 @@
{ {
"metadata": { "metadata": {
"name": "", "name": "",
"signature": "sha256:d8ba69c66769cf62e5201b70ed7d717913017f6f09492848ce164b50068bd2ba" "signature": "sha256:5e808c95d2003c791e04a26d378bc816b2010a59171244a18d73487060d9e029"
}, },
"nbformat": 3, "nbformat": 3,
"nbformat_minor": 0, "nbformat_minor": 0,
@ -79,7 +79,8 @@
"- [Creating copies of mutable objects](#copy_mutable)\n", "- [Creating copies of mutable objects](#copy_mutable)\n",
"- [Key differences between Python 2 and 3](#python_differences)\n", "- [Key differences between Python 2 and 3](#python_differences)\n",
"- [Function annotations - What are those `->`'s in my Python code?](#function_annotation)\n", "- [Function annotations - What are those `->`'s in my Python code?](#function_annotation)\n",
"- [Abortive statements in `finally` blocks](#finally_blocks)" "- [Abortive statements in `finally` blocks](#finally_blocks)\n",
"- [Assigning types to variables as values](#variable_types)"
] ]
}, },
{ {
@ -922,7 +923,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"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), to avoid syntax error in old (but perfectly working) code, `bool` was added as a subclass of `int` in Python 2.3.\n", "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",
"\n", "\n",
"Original source: [http://www.peterbe.com/plog/bool-is-int](http://www.peterbe.com/plog/bool-is-int)" "Original source: [http://www.peterbe.com/plog/bool-is-int](http://www.peterbe.com/plog/bool-is-int)"
] ]
@ -933,7 +934,7 @@
"input": [ "input": [
"print('isinstance(True, int):', isinstance(True, int))\n", "print('isinstance(True, int):', isinstance(True, int))\n",
"print('True + True:', True + True)\n", "print('True + True:', True + True)\n",
"print('3*True:', 3*True)\n", "print('3*True + True:', 3*True + True)\n",
"print('3*True - False:', 3*True - False)\n" "print('3*True - False:', 3*True - False)\n"
], ],
"language": "python", "language": "python",
@ -945,12 +946,12 @@
"text": [ "text": [
"isinstance(True, int): True\n", "isinstance(True, int): True\n",
"True + True: 2\n", "True + True: 2\n",
"3*True: 3\n", "3*True + True: 4\n",
"3*True - False: 3\n" "3*True - False: 3\n"
] ]
} }
], ],
"prompt_number": 16 "prompt_number": 28
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
@ -979,11 +980,11 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Remember the [\"consuming generators\"](consuming_generators)? This example is somewhat related, but the result might still come unexpected. \n", "Remember the section about the [\"consuming generators\"](consuming_generators)? This example is somewhat related, but the result might still come unexpected. \n",
"\n", "\n",
"(Original source: [http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html](http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html))\n", "(Original source: [http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html](http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html))\n",
"\n", "\n",
"In the first example below, where we call a `lambda` function in a list comprehension, the value `i` is dereferenced every time we call `lambda` within the scope of the list comprehension. Since the list is already constructed when we `for-loop` through the list, it is set to the last value 4." "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 is already constructed when we `for-loop` through the list, it will be set to the last value 4."
] ]
}, },
{ {
@ -1009,7 +1010,7 @@
] ]
} }
], ],
"prompt_number": 11 "prompt_number": 29
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
@ -1041,7 +1042,7 @@
] ]
} }
], ],
"prompt_number": 9 "prompt_number": 30
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
@ -1106,7 +1107,7 @@
] ]
} }
], ],
"prompt_number": 33 "prompt_number": 31
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
@ -1484,8 +1485,8 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Not, really (or significantly, see the benchmarks below). So what's the reason to prefer one over the other?\n", "\"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 list methods \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" "- use generators when you are dealing with huge collections to avoid memory issues"
] ]
}, },
@ -1699,7 +1700,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"It can be really dangerous to modify a list when iterating through - it is a very common pitfall that can cause unintended behavior! \n", "It can be really dangerous to modify a list when iterating through it - this is a very common pitfall that can cause unintended behavior! \n",
"Look at the following examples, and for a fun exercise: try to figure out what is going on before you skip to the solution!" "Look at the following examples, and for a fun exercise: try to figure out what is going on before you skip to the solution!"
] ]
}, },
@ -2865,6 +2866,78 @@
"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!" "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": [
"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."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a_var = str\n",
"a_var(123)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 1,
"text": [
"'123'"
]
}
],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from random import choice\n",
"\n",
"a, b, c = float, int, str\n",
"for i in range(5):\n",
" j = choice([a,b,c])(i)\n",
" print(j, type(j))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0 <class 'int'>\n",
"1 <class 'int'>\n",
"2.0 <class 'float'>\n",
"3 <class 'str'>\n",
"4 <class 'int'>\n"
]
}
],
"prompt_number": 4
},
{ {
"cell_type": "code", "cell_type": "code",
"collapsed": false, "collapsed": false,