473,776 Members | 1,650 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Feedback on Until recipe

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__(sel f):
return self.ans

Apr 24 '07 #1
7 1482
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__(sel f):
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.

regards
Steve
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

Apr 24 '07 #2
On Apr 24, 11:08 am, Thomas Nelson <t...@mail.utex as.eduwrote:
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__(sel f):
return self.ans
Class-level "yet" variable not a good idea. Loops can be nested:

i = 0
# this should loop once, since test is logically at the end of the
loop
while Until(lambda : i < 0 ):
print "hello"
i += 1
j = 0
while Until(lambda : j < 0 ):
print "byebye"
j += 1

This loops forever.

After tinkering with this a bit, I can see why you need a class
variable. In your outer loop, "Until(lamb da : i < 0)" is evaluated
every time around the loop, creating a new Until object, so you can't
preserve looping state in the object, you have to do it in the class.

I used your idea to create an instance-level Until that survives
looping, but the requirements for construction are still onerous. In
essence, the instance-level util defers the break-on-condition by one
loop iteration.

class Until:
"""
>>i = 0
while Until(lambda: i<3):
... print "hello"
... i += 1
hello
hello
hello
>>while Until(lambda: i<2):
... print "hello"
hello
"""
def __init__(self, mybool):
self.lastTest = True
self.mybool = mybool

def __nonzero__(sel f):
ret,self.lastTe st = self.lastTest,s elf.mybool()
return ret

i = 0
uCond1 = Until(lambda : i < 0 )
uCond2 = Until(lambda : j < 0 )
while uCond1:
print "hello"
i += 1
j = 0
while uCond2:
print "byebye"
j += 1

-- Paul

Apr 26 '07 #3
I moved the state into the Until instance vs. the Until class, so that
it now supports nesting. But the calling syntax is even uglier - but
necessary to avoid creating a new Until instance each time around.
That is "while Until(blah):" evaluates and constructs a new Until
instance each time around the loop, so that is why the state had to be
kept in a class-level variable in your original design (which is why
nesting doesn't work).

class Until:
def __init__(self, mybool):
self.lastTest = True
self.mybool = mybool

def __nonzero__(sel f):
ret,self.lastTe st = self.lastTest,s elf.mybool()
return ret

i = 0
u1 = Until(lambda : i < 0 )
while u1:
print "hello"
i += 1
j = 0
u2 = Until(lambda : j < 0 )
while u2:
print "byebye"
j += 1

Apr 26 '07 #4
On Wed, 2007-04-25 at 19:11 -0700, Paul McGuire wrote:
I moved the state into the Until instance vs. the Until class, so that
it now supports nesting. But the calling syntax is even uglier - but
necessary to avoid creating a new Until instance each time around.
That is "while Until(blah):" evaluates and constructs a new Until
instance each time around the loop, so that is why the state had to be
kept in a class-level variable in your original design (which is why
nesting doesn't work).

class Until:
def __init__(self, mybool):
self.lastTest = True
self.mybool = mybool

def __nonzero__(sel f):
ret,self.lastTe st = self.lastTest,s elf.mybool()
return ret

i = 0
u1 = Until(lambda : i < 0 )
while u1:
print "hello"
i += 1
j = 0
u2 = Until(lambda : j < 0 )
while u2:
print "byebye"
j += 1
Using iterators is a way around the problem of making a new instance
every time around the loop, but the calling syntax is not much nicer
since it is shoehorned into a for-loop. Note that I've renamed the beast
in order to reflect what it actually does: The loop body is repeated as
long as the given condition is true.

class RepeatAsLongAs( object):
def __init__(self, cond):
self.cond = cond
self.previousTe st = True
def __iter__(self):
return self
def next(self):
ret, self.previousTe st = self.previousTe st, self.cond()
if not ret: raise StopIteration
return ret

i = 0
for _ in RepeatAsLongAs( lambda: i<0):
print "hello"
i += 1
j = 0
for _ in RepeatAsLongAs( lambda: j<0):
print "byebye"
j += 1

Having said that, I don't see myself ever using such a beast. The
equivalent code

while True:
# do something
if until_condition : break

is much more concise, much easier to understand, and it shows explicitly
that the condition is checked after the loop body is executed.

-Carsten
Apr 26 '07 #5
On 2007-04-24, Thomas Nelson <th*@mail.utexa s.eduwrote:
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.
Maybe we should try to get the developers revive PEP 315.

This PEP whould introduce a do-while statement that looks
like the folowing:

do
statements
while condition
statements
this would be equivallent to:

while 1:
statements
if not condition:
break
statements
Those wanting something like:

repeat
statements
until condition
Could then write something like:

do
statements
while not condition
pass
Still not the most elegant but a vast improvement IMO.

--
Antoon Pardon
Apr 26 '07 #6
On Apr 26, 11:58 am, Antoon Pardon <apar...@forel. vub.ac.bewrote:
On 2007-04-24, Thomas Nelson <t...@mail.utex as.eduwrote:
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.

Maybe we should try to get the developers revive PEP 315.

This PEP whould introduce a do-while statement that looks
like the folowing:

do
statements
while condition
statements

this would be equivallent to:

while 1:
statements
if not condition:
break
statements

Those wanting something like:

repeat
statements
until condition

Could then write something like:

do
statements
while not condition
pass

Still not the most elegant but a vast improvement IMO.
At http://mail.python.org/pipermail/pyt...ry/060718.html
Raymond Hettinger suggested removing the final colon after the 'while'
if there's no statement after it, which I agree with, although I would
prefer 'repeat' instead of 'do' (IMHO that doesn't suggest repetition
clearly enough):

repeat:
statements
while condition:
statements

and:

repeat:
statements
while condition

Apr 26 '07 #7
On 2007-04-26, MRAB <go****@mrabarn ett.plus.comwro te:
At http://mail.python.org/pipermail/pyt...ry/060718.html
Raymond Hettinger suggested removing the final colon after the 'while'
if there's no statement after it, which I agree with, although I would
prefer 'repeat' instead of 'do' (IMHO that doesn't suggest repetition
clearly enough):

repeat:
statements
while condition:
statements

and:

repeat:
statements
while condition
I wouldn't object to this. But more important than how it will look like
IMO is that it gets implemented. Acoording to your URL there is little
chance that this will be implemented before Py3k. A pity.

--
Antoon Pardon
Apr 27 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1399
by: Dan Perl | last post by:
pyfmf is a project I started a few months ago and that is registered with sourceforge (http://pyfmf.sourceforge.net, http://sourceforge.net/projects/pyfmf). It consists of a framework for file management, with a console based toolkit (zigo) and a graphical platform (zago) based on the framework. Both zigo and zago are still alpha releases, addressed only to python enthusiasts. I just released a new version of zigo and the first release...
8
1774
by: Michele Simionato | last post by:
I was playing with string.Template in Python 2.4 and I came out with the following recipe: import sys from string import Template def merge(*dictionaries): """Merge from right (i.e. the rightmost dictionary has the precedence).""" merg = {} for d in dictionaries:
36
42429
by: Remi Villatel | last post by:
Hi there, There is always a "nice" way to do things in Python but this time I can't find one. What I'm trying to achieve is a conditionnal loop of which the condition test would be done at the end so the loop is executed at least once. It's some way the opposite of "while". So far, all I got is:
1
1762
by: Nicholas Zhou | last post by:
We'd like your help. The ChineseFoodDIY web site has just been redesigned. We have just updated it to include some great new tips and it now has an entirely new look. I think that I'm "too involved" in the design to evaluate it objectively. If some of you would look it over and give some solid input, it would be most appreciated. My questions are: 1. When you first arrived, was the subject clear? 2. Does it sound like a good idea? Does...
1
1272
by: Dgates | last post by:
I'm learning ASP.NET, C# and VB.NET, and hoping to get some feedback from more experienced programmers on a few issues regarding efficient, readable, well-organized code. I'm trying to program anything I do in the best possible "style," even if it's just a silly experiment (e.g., a simulation to find out the average number of times you have to roll a die before all six sides have come up). With quickie experiments at home, alone, it's...
8
6646
by: Richard Hollenbeck | last post by:
I have a recipe database that I've been building but I haven't yet put any of the ingredients in because of a little problem of normalization. If I build a table of ingredients, all the recipes will have one or more ingredient(s), but no set number of ingredients, so that doesn't seem possible to normalize it. Any given recipe would use one, some, or all of the ingredients within the ingredients table, so I can't imagine an indefinite...
6
14401
by: placid | last post by:
Hi all, Im using the cmd module and i have command that loops and keeps on printing text, what i want to be able to do is loop until the user presses a particular key, say Q/q ? I tried the following code; line = raw_input ("press q to abort") while line != "q":
17
1904
by: Ron Adam | last post by:
I put together the following module today and would like some feedback on any obvious problems. Or even opinions of weather or not it is a good approach. While collating is not a difficult thing to do for experienced programmers, I have seen quite a lot of poorly sorted lists in commercial applications, so it seems it would be good to have an easy to use ready made API for collating. I tried to make this both easy to use and flexible. ...
0
918
by: Thomas Nelson | last post by:
Occasionally people post complaining about the lack of a "repeat...until" structure in python. I thought about it and came up with this recipe that I like. The only ugly thing is having to use lambdas, otherwise it's very terse and readable. Tell me what you think, and if anyone besides me thinks they might use it, I'll post it to the python cookbook. Thanks for your time, Tom
0
9628
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9464
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10289
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10120
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9923
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8952
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7471
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4031
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2860
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.