Skip to content

Instantly share code, notes, and snippets.

@jabooth
Created January 15, 2014 15:20
Show Gist options
  • Save jabooth/8438129 to your computer and use it in GitHub Desktop.
Save jabooth/8438129 to your computer and use it in GitHub Desktop.
Short example of closure in Python
Display the source blob
Display the rendered blob
Raw
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"# prints it's argument, and kwargs.\n",
"def foo(x, **kwargs):\n",
" print 'x: {}'.format(x)\n",
" print 'kwargs: {}'.format(kwargs)\n",
" \n",
"\n",
"# invokes whatever function it is passed\n",
"# with a fixed argument.\n",
"def bar(fctn):\n",
" # note, I never set kwargs\n",
" fctn('from boo!')\n",
"\n",
" \n",
"# calls bar using the foo function \n",
"def bar_calling_foo():\n",
" bar(foo)\n",
"\n",
"\n",
"# passes foo with kwargs filled in to bar\n",
"# who then calls it.\n",
"def bar_calling_foo_with_kwargs(**kwargs):\n",
" \n",
" # note that the 'a' here is totally seperate\n",
" # to the 'x' above. Although the name is different\n",
" # it works just fine - all we care about is the \n",
" # position of the arguments.\n",
" def foo_closure(a):\n",
" # a wrapper, closes over the kwargs\n",
" return foo(a, **kwargs)\n",
" \n",
" # invoke bar, passing our closure.\n",
" # foo_closure will still enjoy access to our\n",
" # namespace! This is a *closure*.\n",
" bar(foo_closure)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"foo('calling foo directly', hello='world')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"x: calling foo directly\n",
"kwargs: {'hello': 'world'}\n"
]
}
],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"bar(foo)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"x: from boo!\n",
"kwargs: {}\n"
]
}
],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# just putting the above into a function\n",
"bar_calling_foo()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"x: from boo!\n",
"kwargs: {}\n"
]
}
],
"prompt_number": 4
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# now with closure on kwargs\n",
"bar_calling_foo_with_kwargs(pint='delicious')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"x: from boo!\n",
"kwargs: {'pint': 'delicious'}\n"
]
}
],
"prompt_number": 5
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment