Added closure snippet.

This commit is contained in:
Donne Martin 2015-01-26 16:12:30 -05:00
parent 9e87f05f43
commit 84fb0356bf

View File

@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
"signature": "sha256:a37a234cd37895919493dabe7ab645bb2b5e24d9b304ab564e18b59eac4f7a0a"
"signature": "sha256:1c8db5161bc70c65141de06823a3be29e8f58e1668a4090282d39002eabd8adb"
},
"nbformat": 3,
"nbformat_minor": 0,
@ -200,6 +200,95 @@
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Closures"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Closures are dynamically-genearated functions returned by another function. The returned function has access to the variables in the local namespace where it was created."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def make_closure(x):\n",
" def closure():\n",
" print('Secret value is: %s' % x)\n",
" return closure\n",
"\n",
"closure = make_closure(7)\n",
"closure()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Secret value is: 7\n"
]
}
],
"prompt_number": 31
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following function returns a function that keeps track of arguments it has seen."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def make_watcher():\n",
" dict_seen = {}\n",
" \n",
" def watcher(x):\n",
" if x in dict_seen:\n",
" return True\n",
" else:\n",
" dict_seen[x] = True\n",
" return False\n",
" \n",
" return watcher"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 34
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"watcher = make_watcher()\n",
"seq = [1, 1, 2, 3, 5, 8, 13, 2, 5, 13]\n",
"[watcher(x) for x in seq]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 46,
"text": [
"[False, True, False, False, False, False, False, True, True, True]"
]
}
],
"prompt_number": 46
}
],
"metadata": {}