title: Python with statements
body: <p>I'm experimenting with Python's <code>with</code> statements, and I've found that in the following code listing my <code>__init__</code> method gets called twice, while my <code>__exit__</code> method gets called once. This presumably means that there will be a resource leak if this code did anything useful.</p>
  
  <pre><code>class MyResource:
      def __enter__(self):
          print 'Entering MyResource'
          return MyResource()
  
      def __exit__(self, exc_type, exc_value, traceback):
          print 'Cleaning up MyResource'
  
      def __init__(self):
          print 'Constructing MyResource'
  
      def some_function(self):
          print 'Some function'
  
  def main():
      with MyResource() as r:
          r.some_function()
  
  if __name__=='__main__':
      main()
  </code></pre>
  
  <p>This is the program's output:</p>
  
  <pre><code>Constructing MyResource
  Entering MyResource
  Constructing MyResource
  Some function
  Cleaning up MyResource
  </code></pre>
  
  <p>I'm guessing it's because I'm doing something wrong in the <code>with</code> statement, effectively calling the constructor manually. How do I correct this?</p>