|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "metadata": {}, |
| 6 | + "source": [ |
| 7 | + "# With Statement Context Managers\n", |
| 8 | + "\n", |
| 9 | + "When you open a file using `f = open('test.txt')`, the file stays open until you specifically call `f.close()`. Should an exception be raised while working with the file, it remains open. This can lead to vulnerabilities in your code, and inefficient use of resources.\n", |
| 10 | + "\n", |
| 11 | + "A context manager handles the opening and closing of resources, and provides a built-in `try/finally` block should any exceptions occur.\n", |
| 12 | + "\n", |
| 13 | + "The best way to demonstrate this is with an example.\n", |
| 14 | + "\n", |
| 15 | + "### Standard `open()` procedure, with a raised exception:\n" |
| 16 | + ] |
| 17 | + }, |
| 18 | + { |
| 19 | + "cell_type": "code", |
| 20 | + "execution_count": 1, |
| 21 | + "metadata": {}, |
| 22 | + "outputs": [ |
| 23 | + { |
| 24 | + "ename": "UnsupportedOperation", |
| 25 | + "evalue": "not readable", |
| 26 | + "output_type": "error", |
| 27 | + "traceback": [ |
| 28 | + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", |
| 29 | + "\u001b[1;31mUnsupportedOperation\u001b[0m Traceback (most recent call last)", |
| 30 | + "\u001b[1;32m<ipython-input-1-ad7a2000735b>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0mp\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'oops.txt'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'a'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mreadlines\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[0mp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", |
| 31 | + "\u001b[1;31mUnsupportedOperation\u001b[0m: not readable" |
| 32 | + ] |
| 33 | + } |
| 34 | + ], |
| 35 | + "source": [ |
| 36 | + "p = open('oops.txt','a')\n", |
| 37 | + "p.readlines()\n", |
| 38 | + "p.close()" |
| 39 | + ] |
| 40 | + }, |
| 41 | + { |
| 42 | + "cell_type": "markdown", |
| 43 | + "metadata": {}, |
| 44 | + "source": [ |
| 45 | + "Let's see if we can modify our file:" |
| 46 | + ] |
| 47 | + }, |
| 48 | + { |
| 49 | + "cell_type": "code", |
| 50 | + "execution_count": 2, |
| 51 | + "metadata": {}, |
| 52 | + "outputs": [ |
| 53 | + { |
| 54 | + "data": { |
| 55 | + "text/plain": [ |
| 56 | + "13" |
| 57 | + ] |
| 58 | + }, |
| 59 | + "execution_count": 2, |
| 60 | + "metadata": {}, |
| 61 | + "output_type": "execute_result" |
| 62 | + } |
| 63 | + ], |
| 64 | + "source": [ |
| 65 | + "p.write('add more text')" |
| 66 | + ] |
| 67 | + }, |
| 68 | + { |
| 69 | + "cell_type": "markdown", |
| 70 | + "metadata": {}, |
| 71 | + "source": [ |
| 72 | + "Ouch! I may not have wanted to do that until I traced the exception! Unfortunately, the exception prevented the last line, `p.close()` from running. Let's close the file manually:" |
| 73 | + ] |
| 74 | + }, |
| 75 | + { |
| 76 | + "cell_type": "code", |
| 77 | + "execution_count": 3, |
| 78 | + "metadata": {}, |
| 79 | + "outputs": [], |
| 80 | + "source": [ |
| 81 | + "p.close()" |
| 82 | + ] |
| 83 | + }, |
| 84 | + { |
| 85 | + "cell_type": "markdown", |
| 86 | + "metadata": {}, |
| 87 | + "source": [ |
| 88 | + "### Protect the file with `try/except/finally`\n", |
| 89 | + "\n", |
| 90 | + "A common workaround is to insert a `try/except/finally` clause to close the file whenever an exception is raised:\n" |
| 91 | + ] |
| 92 | + }, |
| 93 | + { |
| 94 | + "cell_type": "code", |
| 95 | + "execution_count": 4, |
| 96 | + "metadata": {}, |
| 97 | + "outputs": [ |
| 98 | + { |
| 99 | + "name": "stdout", |
| 100 | + "output_type": "stream", |
| 101 | + "text": [ |
| 102 | + "An exception was raised!\n" |
| 103 | + ] |
| 104 | + } |
| 105 | + ], |
| 106 | + "source": [ |
| 107 | + "p = open('oops.txt','a')\n", |
| 108 | + "try:\n", |
| 109 | + " p.readlines()\n", |
| 110 | + "except:\n", |
| 111 | + " print('An exception was raised!')\n", |
| 112 | + "finally:\n", |
| 113 | + " p.close()" |
| 114 | + ] |
| 115 | + }, |
| 116 | + { |
| 117 | + "cell_type": "markdown", |
| 118 | + "metadata": {}, |
| 119 | + "source": [ |
| 120 | + "Let's see if we can modify our file this time:" |
| 121 | + ] |
| 122 | + }, |
| 123 | + { |
| 124 | + "cell_type": "code", |
| 125 | + "execution_count": 5, |
| 126 | + "metadata": {}, |
| 127 | + "outputs": [ |
| 128 | + { |
| 129 | + "ename": "ValueError", |
| 130 | + "evalue": "I/O operation on closed file.", |
| 131 | + "output_type": "error", |
| 132 | + "traceback": [ |
| 133 | + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", |
| 134 | + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", |
| 135 | + "\u001b[1;32m<ipython-input-5-1209a18e617d>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'add more text'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", |
| 136 | + "\u001b[1;31mValueError\u001b[0m: I/O operation on closed file." |
| 137 | + ] |
| 138 | + } |
| 139 | + ], |
| 140 | + "source": [ |
| 141 | + "p.write('add more text')" |
| 142 | + ] |
| 143 | + }, |
| 144 | + { |
| 145 | + "cell_type": "markdown", |
| 146 | + "metadata": {}, |
| 147 | + "source": [ |
| 148 | + "Excellent! Our file is safe.\n", |
| 149 | + "\n", |
| 150 | + "### Save steps with `with`\n", |
| 151 | + "\n", |
| 152 | + "Now we'll employ our context manager. The syntax follows `with [resource] as [target]: do something`" |
| 153 | + ] |
| 154 | + }, |
| 155 | + { |
| 156 | + "cell_type": "code", |
| 157 | + "execution_count": 6, |
| 158 | + "metadata": {}, |
| 159 | + "outputs": [ |
| 160 | + { |
| 161 | + "ename": "UnsupportedOperation", |
| 162 | + "evalue": "not readable", |
| 163 | + "output_type": "error", |
| 164 | + "traceback": [ |
| 165 | + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", |
| 166 | + "\u001b[1;31mUnsupportedOperation\u001b[0m Traceback (most recent call last)", |
| 167 | + "\u001b[1;32m<ipython-input-6-7ccc44e332f9>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'oops.txt'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'a'\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mp\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mreadlines\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", |
| 168 | + "\u001b[1;31mUnsupportedOperation\u001b[0m: not readable" |
| 169 | + ] |
| 170 | + } |
| 171 | + ], |
| 172 | + "source": [ |
| 173 | + "with open('oops.txt','a') as p:\n", |
| 174 | + " p.readlines()" |
| 175 | + ] |
| 176 | + }, |
| 177 | + { |
| 178 | + "cell_type": "markdown", |
| 179 | + "metadata": {}, |
| 180 | + "source": [ |
| 181 | + "Can we modify the file?" |
| 182 | + ] |
| 183 | + }, |
| 184 | + { |
| 185 | + "cell_type": "code", |
| 186 | + "execution_count": 7, |
| 187 | + "metadata": {}, |
| 188 | + "outputs": [ |
| 189 | + { |
| 190 | + "ename": "ValueError", |
| 191 | + "evalue": "I/O operation on closed file.", |
| 192 | + "output_type": "error", |
| 193 | + "traceback": [ |
| 194 | + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", |
| 195 | + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", |
| 196 | + "\u001b[1;32m<ipython-input-7-1209a18e617d>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwrite\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'add more text'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", |
| 197 | + "\u001b[1;31mValueError\u001b[0m: I/O operation on closed file." |
| 198 | + ] |
| 199 | + } |
| 200 | + ], |
| 201 | + "source": [ |
| 202 | + "p.write('add more text')" |
| 203 | + ] |
| 204 | + }, |
| 205 | + { |
| 206 | + "cell_type": "markdown", |
| 207 | + "metadata": {}, |
| 208 | + "source": [ |
| 209 | + "Great! With just one line of code we've handled opening the file, enclosing our code in a `try/finally` block, and closing our file all at the same time.\n", |
| 210 | + "\n", |
| 211 | + "Now you should have a basic understanding of context managers." |
| 212 | + ] |
| 213 | + } |
| 214 | + ], |
| 215 | + "metadata": { |
| 216 | + "kernelspec": { |
| 217 | + "display_name": "Python 3", |
| 218 | + "language": "python", |
| 219 | + "name": "python3" |
| 220 | + }, |
| 221 | + "language_info": { |
| 222 | + "codemirror_mode": { |
| 223 | + "name": "ipython", |
| 224 | + "version": 3 |
| 225 | + }, |
| 226 | + "file_extension": ".py", |
| 227 | + "mimetype": "text/x-python", |
| 228 | + "name": "python", |
| 229 | + "nbconvert_exporter": "python", |
| 230 | + "pygments_lexer": "ipython3", |
| 231 | + "version": "3.6.2" |
| 232 | + } |
| 233 | + }, |
| 234 | + "nbformat": 4, |
| 235 | + "nbformat_minor": 2 |
| 236 | +} |
0 commit comments