title: Making a class perform tasks when it exits scope of `with` statement
body: <p>Is there a class attribute that I can override to make an instance of a class perform something before it exits the scope of a <code>with</code> statement?</p>
  
  <p>For example, we can ensure that we close a file handle when we're done with it:</p>
  
  <pre><code>with open(PATH, 'wb') as f:
      f.write("SOME TEXT")
  </code></pre>
  
  <p>If I wrote a class that needs a writer to persist for the lifetime of the class like this:</p>
  
  <pre><code>class MyWriter(object):
  
     def __init__(self, path):
         self.f = open(path, 'wb')
         self.buffer = ''
  
     def write(self, text):
         self.buffer += text
         # Just a toy example, naively relying on file system
         # page cache should outperform this 
         if len(self.buffer) &gt;= 4096:
             self.flush()
  
     def flush(self):
         f.write(self.buffer)
         self.buffer = ''
  
     def close(self):
         self.flush()
         self.f.close()
  </code></pre>
  
  <p>then I would like to force a call of <code>.close()</code> and flush before I exit the scope of <code>with</code>:</p>
  
  <pre><code>with MyWriter(PATH) as mw:
      mw.write("SOME TEXT")
  </code></pre>