Skip to content

Instantly share code, notes, and snippets.

@Back2Basics
Created October 20, 2016 19:08
Show Gist options
  • Save Back2Basics/23d7b5d79fbc047c111a5232fcf909a4 to your computer and use it in GitHub Desktop.
Save Back2Basics/23d7b5d79fbc047c111a5232fcf909a4 to your computer and use it in GitHub Desktop.
Context Mangers
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"aname = open('name_of_file.txt', 'w')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"11"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"aname.write('hello world')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Warning: If you try to read the file without closing it you might not see the data."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"aname.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now you can open the file and see the data written."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Those are the 3 steps to opening a file. There is an easier way."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello world\n"
]
}
],
"source": [
"with open('nameoffile.txt','r') as bname:\n",
" #do stuff with bname here like:\n",
" print(bname.read())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However if you try to read it again when the indent is over"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "ValueError",
"evalue": "I/O operation on closed file.",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-5-25e1b82b7dc4>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mbname\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: I/O operation on closed file."
]
}
],
"source": [
"bname.read()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The \"with\" statement automatically closed the file after the code indent finished."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Well that's a nifty trick but HOW did the with statement know how to do that?\n",
"\n",
"The trick was in the open class."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#WARNING don't run this cell. if you did, simply run \"Kernel\" -> \"Restart\" in the menu's\n",
"#the real open class is much more involved. I've shortened it for a Python beginners tutoral.\n",
"\n",
"class open():\n",
" def __init__(self, filename, read_write_attr):\n",
" self.filename = filename\n",
" self.read_write_attr = read_write_attr\n",
" \n",
" def __enter__(self):\n",
" #open the file here\n",
" pass\n",
"\n",
" def __exit__(self, *thisisneeded):\n",
" #close the file here\n",
" pass\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The \"with\" statement is looking for 2 functions in the class: __enter__() and __exit__()\n",
"it's going to run the __enter__ before the block of code underneath is run\n",
"and the __exit__ function after the block of code is finished.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This would be a good idea when you have a class that has a start/stop or beginning/end or run/reverse types of ideas like.\n",
"* roomba returning to it's charging station\n",
"* starting/stopping or stopping/starting computer services\n",
"* "
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"class html():\n",
" def __init__(self, tag):\n",
" self.tag = tag\n",
" \n",
" def __enter__(self):\n",
" print(\"<{}>\".format(self.tag))\n",
"\n",
" def __exit__(self, *this_is_needed):\n",
" print(\"</{}>\".format(self.tag))\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<My_New_tag>\n",
"this will be surrounded by the html my made up tag name\n",
"</My_New_tag>\n"
]
}
],
"source": [
"with html('My_New_tag'):\n",
" print('this text will be surrounded by the html my made up tag name')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"here is the python help info on CONTEXTMANAGER"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"With Statement Context Managers\n",
"*******************************\n",
"\n",
"A *context manager* is an object that defines the runtime context to\n",
"be established when executing a \"with\" statement. The context manager\n",
"handles the entry into, and the exit from, the desired runtime context\n",
"for the execution of the block of code. Context managers are normally\n",
"invoked using the \"with\" statement (described in section *The with\n",
"statement*), but can also be used by directly invoking their methods.\n",
"\n",
"Typical uses of context managers include saving and restoring various\n",
"kinds of global state, locking and unlocking resources, closing opened\n",
"files, etc.\n",
"\n",
"For more information on context managers, see *Context Manager Types*.\n",
"\n",
"object.__enter__(self)\n",
"\n",
" Enter the runtime context related to this object. The \"with\"\n",
" statement will bind this method's return value to the target(s)\n",
" specified in the \"as\" clause of the statement, if any.\n",
"\n",
"object.__exit__(self, exc_type, exc_value, traceback)\n",
"\n",
" Exit the runtime context related to this object. The parameters\n",
" describe the exception that caused the context to be exited. If the\n",
" context was exited without an exception, all three arguments will\n",
" be \"None\".\n",
"\n",
" If an exception is supplied, and the method wishes to suppress the\n",
" exception (i.e., prevent it from being propagated), it should\n",
" return a true value. Otherwise, the exception will be processed\n",
" normally upon exit from this method.\n",
"\n",
" Note that \"__exit__()\" methods should not reraise the passed-in\n",
" exception; this is the caller's responsibility.\n",
"\n",
"See also: **PEP 0343** - The \"with\" statement\n",
"\n",
" The specification, background, and examples for the Python \"with\"\n",
" statement.\n",
"\n",
"Related help topics: with\n",
"\n"
]
}
],
"source": [
"help('CONTEXTMANAGERS')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment