Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anandology/5652394 to your computer and use it in GitHub Desktop.
Save anandology/5652394 to your computer and use it in GitHub Desktop.
Advanced Python Workshop - Class Notes
Display the source blob
Display the rendered blob
Raw
{
"metadata": {
"name": "4 - Context Managers (Advanced Python Workshop)"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Context Managers"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The `with` statement"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"f = open(\"a.txt\", \"w\")\n",
"f.write(\"hello\")\n",
"f.close()"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"with open(\"a.txt\", \"w\") as f:\n",
" f.write(\"hello\")"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 4
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"f = open(\"a.txt\")\n",
"dir(f)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 7,
"text": [
"['__class__',\n",
" '__delattr__',\n",
" '__doc__',\n",
" '__enter__',\n",
" '__exit__',\n",
" '__format__',\n",
" '__getattribute__',\n",
" '__hash__',\n",
" '__init__',\n",
" '__iter__',\n",
" '__new__',\n",
" '__reduce__',\n",
" '__reduce_ex__',\n",
" '__repr__',\n",
" '__setattr__',\n",
" '__sizeof__',\n",
" '__str__',\n",
" '__subclasshook__',\n",
" 'close',\n",
" 'closed',\n",
" 'encoding',\n",
" 'errors',\n",
" 'fileno',\n",
" 'flush',\n",
" 'isatty',\n",
" 'mode',\n",
" 'name',\n",
" 'newlines',\n",
" 'next',\n",
" 'read',\n",
" 'readinto',\n",
" 'readline',\n",
" 'readlines',\n",
" 'seek',\n",
" 'softspace',\n",
" 'tell',\n",
" 'truncate',\n",
" 'write',\n",
" 'writelines',\n",
" 'xreadlines']"
]
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Example: chdir"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import os\n",
"class chdir:\n",
" def __init__(self, dir):\n",
" self.dir = dir\n",
" print \"__init__\"\n",
" \n",
" def __enter__(self):\n",
" print \"__enter__\"\n",
" self.olddir = os.getcwd()\n",
" os.chdir(self.dir)\n",
" return self\n",
" \n",
" def __exit__(self, *a):\n",
" print \"__exit__\"\n",
" os.chdir(self.olddir)\n",
"\n",
"print os.getcwd()\n",
"print \"before with\"\n",
"with chdir(\"/tmp\") as x:\n",
" print os.getcwd()\n",
"print \"after with\"\n",
"print os.getcwd()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"/Users/anand/Dropbox/Trainings/2013/advancedpython-may2013\n",
"before with\n",
"__init__\n",
"__enter__\n",
"/private/tmp\n",
"__exit__\n",
"after with\n",
"/Users/anand/Dropbox/Trainings/2013/advancedpython-may2013\n"
]
}
],
"prompt_number": 21
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Problem** Write a context manager `capture_output` to capture stdout inside a with block.\n",
"\n",
" with capture_output() as buf:\n",
" print \"hello\"\n",
"\n",
" out = buf.getvalue()\n",
" print \"captured\", repr(out)\n",
"\n",
"Hint: See `StringIO.StringIO` and `sys.stdout`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lets try to understand how to capture output without context managers."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import sys\n",
"from StringIO import StringIO\n",
"\n",
"oldstdout = sys.stdout\n",
"buf = StringIO()\n",
"sys.stdout = buf\n",
"print \"hello\"\n",
"print \"world\"\n",
"sys.stdout = oldstdout\n",
"print \"captured\", repr(buf.getvalue())"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"captured 'hello\\nworld\\n'\n"
]
}
],
"prompt_number": 8
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# solution\n",
"\n",
"from StringIO import StringIO\n",
"import sys\n",
"\n",
"class capture_output:\n",
" def __init__(self):\n",
" self.buf = StringIO()\n",
"\n",
" def __enter__(self):\n",
" self.oldstdout = sys.stdout\n",
" sys.stdout = self.buf\n",
" return self.buf\n",
" \n",
" def __exit__(self, type, exc, traceback):\n",
" sys.stdout = self.oldstdout\n",
" \n",
"#with capture_output() as buf:\n",
"# print \"hello\"\n",
"\n",
"capture_output()\n",
"\n",
"print \"hello\"\n",
"\n",
"#out = buf.getvalue()\n",
"#print \"captured\", repr(out)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"hello\n"
]
}
],
"prompt_number": 6
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Example: ignore_exception"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class ignore_exception:\n",
" def __init__(self):\n",
" pass\n",
"\n",
" def __enter__(self):\n",
" pass\n",
" \n",
" def __exit__(self, type, exc, traceback):\n",
" print type, exc, traceback\n",
" return True\n",
"\n",
"with ignore_exception():\n",
" print \"begin\"\n",
" raise IOError(\"fo\")\n",
" \n",
" "
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"begin\n",
"<type 'exceptions.IOError'> fo <traceback object at 0x102f48998>\n"
]
}
],
"prompt_number": 14
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Problem** Improve the above `ignore_exception` class to ignore only one particular exception. \n",
"\n",
" with ignore_exception(IOError):\n",
" raise IOError(\"foo\")\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment