More elegant way to try running a function X times?
python.list at tim.thechases.com
Thu Nov 20 19:13:21 CET 2008
>>> success = None
>>> for i in range(5):
>>> #Try to fetch public IP
>>> success = CheckIP()
>>> if success:
>>> if not success:
>>> print "Exiting."
>> Though a bit of an abuse, you can use
>> if not any(CheckIP() for _ in range(5)):
>> print "Exiting"
> 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.
As for abuse, the "for _ in iterable" always feels a little hokey
to me. It works, but feels warty.
More information about the Python-list