More elegant way to try running a function X times?
Boris Borcic
bborcic at gmail.com
Thu Nov 20 16:18:36 EST 2008
Tim Chase wrote:
>>>> success = None
>>>> for i in range(5):
>>>> #Try to fetch public IP
>>>> success = CheckIP()
>>>> if success:
>>>> break
>>>> if not success:
>>>> print "Exiting."
>>>> sys.exit()
>>> Though a bit of an abuse, you can use
>>>
>>> if not any(CheckIP() for _ in range(5)):
>>> print "Exiting"
>>> sys.exit()
>>
>> I don't see why you speak of abuse, bit of abuse would be, say if you
>> replaced range(5) by '12345' to win a char; but otoh I think you
>> misspelled any() for all().
>
> The OP's code break'ed (broke?) upon the first success, rather than
> checking all of them. Thus, it would be any() rather than all(). Using
> all() would require 5 successful calls to CheckIP(), rather than
> one-out-of-five successful calls.
Right. So it could also be written " if all(not CheckIP()... ". Perhaps more
closely re-telling the OP's ?
>
> As for abuse, the "for _ in iterable" always feels a little hokey to
> me. It works, but feels warty.
I guess this means you did not learn Prolog before Python ?
Cheers, BB
More information about the Python-list
mailing list