title: How to leave a `with` block without closing the resource?
body: <p>I am trying to achieve something similar to</p>
  <pre class="lang-py prettyprint-override"><code>from tempfile import TemporaryFile
  
  def open_head(file_path):
     with open(file_path, 'r') as f,
          TemporaryFile() as tf:
         for i in range(0,10):
             tf.write(f.read_line())
         return tf
  </code></pre>
  <p>such that the caller gets ownership of the temporary file.</p>
  <p>In particular, I don't want the <code>with</code> statement to close the <code>TemporaryFile</code>. But if anything goes wrong before the <code>return</code>, I still want the <code>TemporaryFile</code> be closed by the <code>with</code> statement.</p>
  <p>Ideally, I would then want to write the caller as</p>
  <pre><code>with open_head(file_path):
      # more code here
  </code></pre>
  <p>Is this possible somehow? E.g. by writing <code>return do_not_close(tf)</code> or some other utility functionality?</p>
  <p>Or am I approaching this completely wrong and there is a more Pythonic way to return a <code>TemporaryFiles</code> or other resources, between functions while guaranteeing exception safety?</p>