A gnarly little python loop

Cameron Simpson cs at zip.com.au
Sun Nov 11 09:48:36 CET 2012


On 11Nov2012 08:56, Stefan Behnel <stefan_ml at behnel.de> wrote:
| Steve Howell, 11.11.2012 04:03:
| > On Nov 10, 2:58 pm, Roy Smith <r... at panix.com> wrote:
| >>     page = 1
| >>     while 1:
| >>         r = api.GetSearch(term="foo", page=page)
| >>         if not r:
| >>             break
| >>         for tweet in r:
| >>             process(tweet)
| >>         page += 1
| >>
| >> It works, but it seems excessively fidgety.  Is there some cleaner way
| >> to refactor this?
| > 
| > I think your code is perfectly readable and clean, but you can flatten
| > it like so:
| > 
| >     def get_tweets(term, get_page):
| >         page_nums = itertools.count(1)
| >         pages = itertools.imap(api.getSearch, page_nums)
| >         valid_pages = itertools.takewhile(bool, pages)
| >         tweets = itertools.chain.from_iterable(valid_pages)
| >         return tweets
| 
| I'd prefer the original code ten times over this inaccessible beast.

Me too.
-- 
Cameron Simpson <cs at zip.com.au>

In an insane society, the sane man must appear insane.
        - Keith A. Schauer <keith at balrog.dseg.ti.com>


More information about the Python-list mailing list