Kushal Agarwal Kushal Agarwal - 4 months ago 8
Python Question

Tweets in Python

def twitter_search(twitter_api,q,max_results=200,**kw):
search_results = twitter_api.search.tweets(q=q,count=100,**kw)
statuses = search_results['statuses']
max_results=min(1000,max_results)
for _ in range(10):
try:
next_results = search_results['search_metadata']['next_results']
except KeyError, e:
break
kwargs = dict([ kv.split('=')
for kv in next_results[1:].split("&") ])
search_results = twitter_api.search.tweets(**kwargs)
statuses += search_results['statuses']
if len(statuses) > max_results:
break
return statuses


results = twitter_search(twitter_api,q,max_results=10)
print json.dumps(results[0], indent =1)


The last line is returning an error that
'NoneType' object has no attribute __getitem__

Answer

You have two issues here:

  1. The return statement is inside the for loop, and might not be reached if the loop hits one of the break statements first. If it is reached, it will return earlier than you want, without running the rest of the loop iterations.

  2. You are assuming results will have at least one element (results[0]). If results is an empty list, this will fail with an IndexError.

Solution:

  1. Move the return statement outside of the for loop (dedent one level).

  2. Check if results: before indexing into it.