title: Calling __enter__ and __exit__ manually
body: <p>I've googled <a href="https://www.google.com/search?hl=en&amp;ie=UTF-8&amp;q=python%20calling%20__enter__()%20manually"><code>calling __enter__ manually</code></a> but with no luck. So let's imagine I have <em>MySQL</em> connector class that uses <code>__enter__</code> and <code>__exit__</code> functions (originally used with <code>with</code> statement) to connect/disconnect from a database.</p>
  
  <p>And let's have a class that uses 2 of these connections (for example for data sync). <em>Note: this is not my real-life scenario, but it seems to be the simplest example</em>. </p>
  
  <p>Easiest way to make it all work together is class like this:</p>
  
  <pre><code>class DataSync(object):
  
      def __init__(self):
          self.master_connection = MySQLConnection(param_set_1)
          self.slave_connection = MySQLConnection(param_set_2)
  
      def __enter__(self):
              self.master_connection.__enter__()
              self.slave_connection.__enter__()
              return self
  
      def __exit__(self, exc_type, exc, traceback):
              self.master_connection.__exit__(exc_type, exc, traceback)
              self.slave_connection.__exit__(exc_type, exc, traceback)
  
      # Some real operation functions
  
  # Simple usage example
  with DataSync() as sync:
      records = sync.master_connection.fetch_records()
      sync.slave_connection.push_records(records)
  </code></pre>
  
  <p><strong>Q</strong>: Is it okay (is there anything wrong) to call <code>__enter__</code>/<code>__exit__</code> manually like this? </p>
  
  <p>Pylint 1.1.0 didn't issue any warnings on this, nor have I found any article about it (google link in the beggining).</p>
  
  <p>And what about calling:</p>
  
  <pre><code>try:
      # Db query
  except MySQL.ServerDisconnectedException:
      self.master_connection.__exit__(None, None, None)
      self.master_connection.__enter__()
      # Retry
  </code></pre>
  
  <p>Is this a good/bad practice? Why?</p>