I have a code looping on a generator. I have to break that loop after the second iteration if it reaches it. To do so I use break
, which raises a GeneratorExit
when it calls the Generator.close()
method.
for page in limit_handled(tweepy.Cursor(..., ..., ...):
while len(the_list) < 400:
for status in page:
def process_status(tweet):
...
...
the_list.append(process_status(status))
break
Would there be a more elegant way which would avoid such an error?
Exception ignored in: <generator object limit_handled at 0x000000003AB300A0>
RuntimeError: generator ignored GeneratorExit
I have seen answers to these two questions : How to take the first N... How to get the n next... but this is not the same issue. In my case, the Generator
uses a Cursor
. Hence, at each iteration it processes a query. I want to stop it querying once at least 400 statuses have been reached, which can happen after the second or the third iteration (a query generally return 200 rows, but it can also be less). Slicing the generator is not an option here. Avoiding to process all the queries (16 total, for approximately 16*200=3200 statuses) is exactly what I want to avoid by Breaking the code after 400 statuses are returned.
Edit: For a better understanding, here is the code for my generator:
def limit_handled(cursor):
global user_timeline_remaining
while True:
if user_timeline_remaining>1:
try:
yield cursor.next()
except BaseException as e:
print('failed_on_CURSOR_NEXT', str(e))
else:
time.sleep(5*60)
try:
data = api.rate_limit_status()
except BaseException as f:
print('failed_on_LIMIT_STATUS', str(f))
user_timeline_remaining = data['remaining_queries']