for loop without variable
Ben Finney
bignose+hates-spam at benfinney.id.au
Wed Jan 9 22:55:04 EST 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.
When you have iteration requirements that don't seem to fit the
built-in types (lists, dicts, generators etc.), turn to 'itertools'
<URL:http://www.python.org/doc/lib/module-itertools> in the standard
library.
>>> from itertools import repeat
>>> def foo():
... import random
... print "Trying ..."
... success = random.choice([True, False])
... return success
...
>>> max_attempts = 10
>>> for foo_attempt in repeat(foo, max_attempts):
... if foo_attempt():
... break
...
Trying ...
Trying ...
Trying ...
Trying ...
Trying ...
Trying ...
>>>
Note that this is possibly more readable than 'for foo_attempt in
[foo] * max_attempts", and is more efficient for large values of
'max_attempts' because 'repeat' returns an iterator instead of
actually allocating the whole sequence.
> I guess based on the replies of everyone my best bet is to leave the
> code the way it is and suck up the warning from pylint.
I think your intent -- "repeat this operation N times" -- is better
expressed by the above code, than by keeping count of something you
don't actually care about.
> I don't want to turn the warning off because catching unused
> variables in the general is useful to me.
Agreed.
--
\ "Dyslexia means never having to say that you're ysror." |
`\ —anonymous |
_o__) |
Ben Finney
More information about the Python-list
mailing list