for loop without variable

Paul Rubin http
Fri Jan 11 06:06:39 CET 2008


erik gartz <eegunnar at yahoo.com> writes:
> The loop performs some actions with web services. The particular
> iteration I'm on isn't important to me. It is only important that I
> attempt the web services that number of times. If I succeed I
> obviously break out of the loop and the containing function (the
> function which has the loop in it) returns True. If all attempts fail
> the containing loop returns False.

This uses an index var, but doesn't leak it outside the genexp, so
I don't know what pylint would say (untested):

   def f():
     return any(attempt_service() for i in xrange(10))

I think the above is pretty natural.  If you really insist on not
using any variables, the below might work (untested):

   from itertools import imap, repeat

   def f():
     return any(imap(apply, repeat(attempt_service, 10)))

it just seems way too obscure though.  Python style seems to favor
spewing extra variables around.



More information about the Python-list mailing list