title: Why "name 'cursor' is not defined" when pyodbc cursor is in main()?
body: <p>I'm running a Python program, condensed below, from the command line, and it gives me an error (<code>name 'cursor' is not defined</code>) and points to the <code>cursor.fetchmany()</code> row near the bottom. However, the program runs as desired if I move the first two rows of <code>main()</code>, the <code>conn</code> and <code>cursor</code> assignments, above and outside of <code>main()</code> into the body of the program. Why doesn't this work when I assign <code>cursor</code> inside <code>main()</code>? I'd love to understand whether this is just a quirk of the pyodbc library, or there is a better way to get it to work from inside <code>main()</code>, or it's actually okay to leave the assignments in the body of the program.</p>
  
  <pre><code>import pyodbc
  import csv
  #   ...other modules...
  
  def main():
      conn = pyodbc.connect(DSN=abcxyz, autocommit=True)
      cursor = conn.cursor()
  #   ...sys.argv assignments and validation...
      pull_data(query_file, start_date, end_date, out_file)
  
  def pull_data(query_file, start_date, end_date, out_file):
  #   ...prepare query as string, date range as list...
      for date in list_dates:
          cursor.execute(query, date)
          append_rows(out_file)
  
  def append_rows(out_file):
      with open(out_file, 'a', newline='') as file:
          writer = csv.writer(file)
          while True:
              results = cursor.fetchmany(chunk_size)
              if not results:
                  break
              for result in results:
                  writer.writerow(result)
  
  if __name__ == '__main__':
      main()
  </code></pre>