title: Python "variable not defined" error when it is
body: <p>Below is the code I have been working on.  I am new to python and programing and have been trying to teach myself.</p>
  
  <p>I get the following error.  But <code>messages</code> is defined so I don't understand.</p>
  
  <pre><code>[ec2-user@ip-172-31-46-164 ~]$ ./twitter_test16.sh
  Traceback (most recent call last):
    File "./twitter_test16.sh", line 53, in &lt;module&gt;
      write_csv('twitter_gmail.csv', messages, append=True)
  NameError: name 'messages' is not defined
  </code></pre>
  
  <p>code:</p>
  
  <pre><code>import csv
  import json
  import oauth2 as oauth
  import urllib
  import sys
  import requests
  import time
  
  CONSUMER_KEY = ""
  CONSUMER_SECRET = ""
  ACCESS_KEY = ""
  ACCESS_SECRET = ""
  
  class TwitterSearch:
      def __init__(self,
          ckey    = CONSUMER_KEY,
          csecret = CONSUMER_SECRET,
          akey    = ACCESS_KEY,
          asecret = ACCESS_SECRET,
          query   = 'https://api.twitter.com/1.1/search/tweets.{mode}?{query}'
      ):
          consumer     = oauth.Consumer(key=ckey, secret=csecret)
          access_token = oauth.Token(key=akey, secret=asecret)
          self.client  = oauth.Client(consumer, access_token)
          self.query   = query
  
      def search(self, q, mode='json', **queryargs):
          queryargs['q'] = q
          query = urllib.urlencode(queryargs)
          return self.client.request(self.query.format(query=query, mode=mode))
  
  def write_csv(fname, rows, header=None, append=False, **kwargs):
      filemode = 'ab' if append else 'wb'
      with open(fname, filemode) as outf:
          out_csv = csv.writer(outf, **kwargs)
          if header:
              out_csv.writerow(header)
          out_csv.writerows(rows)
  
  def main():
      ts = TwitterSearch()
      response, data = ts.search('@gmail.com', result_type='recent')
      js = json.loads(data)
  
  
      # I need to parse the content in js and turn it into a generator expression
      messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', []))
      #
  
  write_csv('twitter_gmail.csv', messages, append=True)
  </code></pre>
  
  <p>I have "messages defined" so I dont know why I am getting an error telling me "messages" is not define.</p>