title: Using a context manager for connecting to a sqlite3 database
body: <p>I wanted to create a <code>class</code> for database access in which the I want the programmer to have an option for using the class in a context manager (the <code>with</code> statement). So I tried with the following code: </p>
  
  <pre><code>class dbAccess:
  
      def __init__(self, fileName):
          self.conn = sql.connect(fileName)
          self.c = conn.cursor()
  
      def __enter__(self, fileName):
          self.conn = sql.connect(fileName)
          self.c = conn.cursor()
  
      def __exit__(self):
          self.conn.close()
  </code></pre>
  
  <p>Now I also want the user to be able to use this outside of a context manager. Just like the file <code>open()</code>. So I want to know how I can know if <code>self.conn</code> is already connected to a database, so that when the user uses this, he/she does not run into a conflict? Basically, I want to do something like:</p>
  
  <pre><code>    def __enter__(self, fileName):
          if not alreadyConnected():
              self.conn = sql.connect(fileName)
              self.c = conn.cursor()
  </code></pre>
  
  <p>So how do I figure out the <code>alreadyConnected</code> function?</p>