[Python-ideas] Immemorial desire for "do-while"-like construction

Josiah Carlson josiah.carlson at gmail.com
Thu Jul 16 02:32:01 CEST 2009


On Wed, Jul 15, 2009 at 5:16 PM, Jan Kaliszewski<zuo at chopin.edu.pl> wrote:
> 16-07-2009 o 00:54 Chris Rebert <pyideas at rebertia.com> wrote:
>
>> You can fix that by just writing it as:
>>
>> while True:
>>    SOME
>>    ACTIONS
>>    HERE
>>    if not CONDITION: break
>
> Yeah, but it's not the same :) because eyes must look for the actual loop
> condition somewhere-within-the-loop (after all, "while True" is common
> idiom with large field of usage, not only in such situations...).
>
> Another solution I invented for myself is to use object which once
> evaluates to True, then always to False, e.g.:
>
>  from itertools import chain, repeat
> class FirstTrue(object):
>       def __init__(self):
>           self._iter = chain([True], repeat(False))
>       def __nonzero__(self):  # __bool__ for Py3k
>           return next(self._iter)
>
> Usage:
>
> first = FirstTrue()
> while first or CONDITION:
>     SOME
>     ACTIONS
>     HERE
>
> or, if we want to *evaluate* CONDITION also at first time:
>
> first = FirstTrue()
> while CONDITION or first:
>     SOME
>     ACTIONS
>     HERE

I usually do:
FIRST = 1
while CONDITION or FIRST:
    FIRST = 0
    SOME
    ACTIONS
    HERE

I use 1/0 instead of True/False because older Pythons loaded numeric
constants faster than the names True/False (is that still the case?)

 - Josiah

>
> Wouldn't be nice to have such factory as built-in or in itertools?
>
> Best regards,
> *j
>
> --
> Jan Kaliszewski <zuo at chopin.edu.pl>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



More information about the Python-ideas mailing list