Feedback on Until recipe

Steve Holden steve at
Tue Apr 24 19:18:12 CEST 2007

Thomas Nelson wrote:
> Occasionally someone posts to this group complaining about the lack of
> "repeat ... until" in python.  I too have occasionally wished for such
> a construct, and after some thinking, I came up with the class below.
> I'm hoping to get some feedback here, and if people besides me think
> they might use it someday, I can put it on the python cookbook.  I'm
> pretty happy with it, the only ugly thing is you have to use a
> lambda.  Ideally i'd like to just see
> while Until(i<3)
> but that doesn't work.
> Please tell me what you think, and thanks for your time.
> Tom
> class Until:
>     """
>     >>> i = 0
>     >>> while Until(lambda: i<3):
>     ...     print "hello"
>     ...     i += 1
>     hello
>     hello
>     hello
>     >>> while Until(lambda: i<2):  #note i still equals 3 here
>     ...     print "hello"
>     hello
>     """
>     yet = True
>     def __init__(self, mybool):
>         if self.__class__.yet or mybool():
>             self.__class__.yet = False
>             self.ans = True
>         else:
>             self.__class__.yet = True
>             self.ans = False
>     def __nonzero__(self):
>             return self.ans
First of all, I have to say it reads horribly. "while Until(...)" is 
supposed to remind us of a *repeat* loop?

Secondly it isn't really what you want because the condition is still 
being evaluated before the loop body is executed, when the idea of a 
repeat loop is to terminate the loop after at least one iteration once 
the condition is true. This is not strictly equivalent to your 
conditions. Temporal logic is tricky.

By the way, isn't it always true that self.ans == not self.__class__.yet 
(and why use a class variable, by the way, doesn't this stop you from 
using nested loops)?

That's about all I can think of offhand. Sorry if it seems a bit 
negative. I'm hoping it will spur you on to a better solution.

Steve Holden       +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd
Skype: holdenweb
Recent Ramblings

More information about the Python-list mailing list