title: Passing objects into yield statement in Python
body: <p>I have a script that makes various read requests from a database (I have many methods similar to the <code>read()</code> method). I'd like to avoid repeating the code for creating and closing the cursor. So I am using a context manager and generator hand-in-hand. (In the below code, <code>db_connection</code> is a mysql connector object.)</p>
  
  <pre><code>from contextlib import contextmanager
  
  class DatabaseReader():
    def __init__(self, db_connection):
      self.db_connection = db_connection
      self.num = num
  
    @contextmanager
    def connect(self):
      cursor = self.db_connection.cursor(buffered=True)
      try:
        yield
      finally:
        cursor.close()
  
    def read(self):
      with self.connect():
        cursor.execute("SELECT * FROM table;")
  </code></pre>
  
  <p>However, calling the 'read' method gives me an <code>AttributeError</code> as <code>cursor</code> is not defined. How can I "pass" the cursor object to the yield statement?</p>