How do I know when I can/should use `with` keyword?
<p>In C#, when an object implements <code>IDisposable</code>, <code>using</code> should be used to guarantee that resources will be cleaned if an exception is thrown. For instance, instead of:</p>

<pre class="lang-cs prettyprint-override"><code>var connection = new SqlConnection(...);
...
connection.Close();
</code></pre>

<p>one needs to write:</p>

<pre class="lang-cs prettyprint-override"><code>using (var connection = new SqlConnection(...))
{
    ...
}
</code></pre>

<p>Therefore, just by looking at the signature of the class, I know exactly whether or not I should initialize the object inside a <code>using</code>.</p>

<p>In Python 3, a similar construct is <code>with</code>. Similarly to C#, it ensures that the resources will be cleaned up automatically when exiting the <code>with</code> context, even if a error is raised.</p>

<p>However, I'm not sure how should I determine whether <code>with</code> should be used or not for a specific class. For instance, <a href="http://initd.org/psycopg/docs/usage.html" rel="nofollow">an example from <code>psycopg</code></a> doesn't use <code>with</code>, which may mean that:</p>

<ul>
<li>I shouldn't either, or:</li>
<li>The example is written for Python 2, or:</li>
<li>The authors of the documentation were unaware of <code>with</code> syntax, or:</li>
<li>The authors decided not to handle exceptional cases for the sake of simplicity.</li>
</ul>

<p>In general, how should I determine whether <code>with</code> should be used when initializing an instance of a specific class (assuming that documentation says nothing on the subject, and that I have access to source code)?</p>

<p>You should use <code>with</code> whenever you need to perform some similar action before and after executing the statement. For example:</p>

<ul>
<li><em>Want to execute SQL query?</em> You need to open and close the connections safely.Use <code>with</code>.</li>
<li><em>Want to perform some action on file?</em> You have to open and close the file safely. Use <code>with</code></li>
<li><em>Want to store some data in temporary file to perform some task?</em> You need to create the directory, and clean it up once you are done. Use <code>with</code>, and so on. . . </li>
</ul>

<p>Everything you want to perform before the query execution, add it to the <code>__enter__()</code> method. And the action to be performed after, add it to the <code>__exit__()</code> method.</p>

<p>One of the nice thing about <code>with</code> is, <em><code>__exit__</code> is executed even if the code within <code>with</code> raises any <code>Exception</code></em></p>

python python-3.x with-statement