Loop until condition is true

R

Remi Villatel

checking if a logical expression is true by comparing it to True is bad
style, and comparing values using "is" is also bad style.

Erm... You totally missed the point. I wrote it this way because, first,
it's perfectly valid Python code and, second and most important, it's also a
valid english sentence.

[CENSORED] I keep for myself how stupid I found your post.
the correct way to write that if-statement is:

Don't try to teach your grandfather how to suck eggs. There is no "correct
way" to code and "superfluous" isn't a synonym of "incorrect".
and yes, the "infinite" while loop is a standard Python pattern. get
used to it.

Grandfathers and eggs. Now, excuse me but I have a group of savage AI
written in bad style Python to tame.
 
S

Steven D'Aprano

Erm... You totally missed the point. I wrote it this way because, first,
it's perfectly valid Python code and, second and most important, it's also a
valid english sentence.

Why is it more important for Python code to be a valid English sentence
than for it to be valid Python code?

Does that mean that instead of writing:

squares = [x**2 for x in range(10)]

you instead write the valid English sentence:

the list of squares is given by the set of x squared for x between 0 and 9
inclusive

?

The point being, I would have thought that most programmers would have put
"being a valid English sentence" right down at the bottom of their list of
optional conditions, and not as the "most important" requirement ahead of
even being valid code.

I also question your understanding of valid English. I don't know about
you, but I usually say "if the apple is on the bench..." and hardly ever
"if the apple is on the bench is true...".

[CENSORED] I keep for myself how stupid I found your post.
Whatever.

the correct way to write that if-statement is:

Don't try to teach your grandfather how to suck eggs.

It must be nice to have learnt everything that there is to learn
about Python. I hope I get there someday.
There is no "correct
way" to code and "superfluous" isn't a synonym of "incorrect".

"if final_condition" will always work.

"if final_condition is True" will break if final_condition is not a bool.
Depending on where final_condition gets its result from, that may or may
not be a high risk. It also relies on an implementation detail, that True
and False are singletons (doubletons?), and will break if that changes.
And finally, since True is just an object, and not a constant like None,
it will break if True gets set to some other value.

In other words, it is not only superfluous but also fragile.
 
S

Shane Hathaway

Remi said:
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:

while True:
some(code)
if final_condition is True:
break
#
#

What I don't find so "nice" is to have to build an infinite loop only to
break it.

FWIW, my own experience is that the "while True" idiom is actually safer
and better than alternatives like do/while. I used to write do/while
loops all the time, but I wound up with more than my fair share of
unintentionally infinite loops. I put too much trust in the syntax: I
expected that since I was using the cleaner construct, I didn't have to
worry about infinite loops.

Now, I think of "while True" not as an infinite loop, but rather as a
sign reminding me to be wary of looping infinitely in a particular spot.
I feel like this has resulted in a lot fewer infinite loops in my own
code. Now I believe that any loop that can't be represented well with
"for" or a conditional "while" has enough inherent complexity to justify
a warning sign, and "while True" has bright yellow flashing lights all
over it. Thus I'm quite in favor of the status quo.

Shane
 
F

Fredrik Lundh

Remi said:
Erm... You totally missed the point. I wrote it this way because, first,
it's perfectly valid Python code and, second and most important, it's also a
valid english sentence.

I suggest looking up "is" in the Python manual instead of looking it
up in a dictionary. (hint: it doesn't do what you think it does, and
code using your "perfectly valid" pattern doesn't always work.)
[CENSORED] I keep for myself how stupid I found your post.

so let's see if everyone who understands how embarrassingly stupid
your post is will keep that to themselves...

</F>
 
V

Ville Vainio

Stelios> Anyway, if you can't wait for 2.5 either use 'while 1:',
Stelios> or pyc[1]

.... and I can't see why people don't want to use 'while 1:' in the
first place, given that everyone can identify the idiom
immediately. It's 4 keystrokes less.
 
G

Greg Lindstrom

A bit off topic, but what does the expression "Don't try to teach your
grandfather how to suck eggs." mean? I've never heard it before and am
curious to the story behind it.

Thanks,
--greg
 
M

Magnus Lycka

Remi said:
Erm... You totally missed the point. I wrote it this way because, first,
it's perfectly valid Python code and, second and most important, it's
also a valid english sentence.

Remi, I think you have failed to understand what Fredrik was
telling you. I can understand that, because he didn't actually
explain the problem. He probably thought it was obvious, but
it seems it wasn't.

"if a is b:" is equivalent to "if id(a) == id(b)". It doesn't
test whether two values are the equal, it tests whether a and b
are the same object. None is a singleton object in Python, but
True is not. (At least not in the Python versions I use.)

That means that you are relying on Python to use a performance
optimization (interning of some common values, in this case
the integer 1, which is what True is in practice).

In some cases, "==" and "is" happens to give the same result.1

But often not.
0

Or, for an example of the opposite:
.... def __cmp__(self, other):
.... return -1
....1

In other words, a test like "if x is None:" makes sense,
since None is a singleton, but "if x is True:" certainly
seems like buggy code that just happens to work. You could
write "if x == True:" without risking a failure in some
Python implementation that doesn't intern True (i.e. 1)
if you are certain that x is 0 or 1, but it's completely
redundant. Why stop there? Why not write
"if x == True == True:" or "if x == True == True == True:"?
These are all logically equivalent. You could also write
"if x and True:", or "if x or not True" :)

I understand what your intentions are: You feel that your
code is easier to understand written the way you did it, but
it stops feeling like that once you have gotten fully into
your head that the expressions (a) and (a == True) are
logically equivalent if a is either True or False.

If you manage to get away from this "x == True" mind-set
you are likely to write better Python code.

First of all, a lot of Python values except 1 (a.k.a. True)
are logically true in a Python expression. It's considered
good form to exploit that. E.g.

if y: z = x / y
if text: print text
if l: cols = len(l[0])

In these cases, adding a "==True", would break the code, and
adding more "correct" comparisions would just clutter the code,
which hides the intent and raises the risk for bugs, and make
it more difficult to keep the code as flexible as Python code
can be. E.g. if you change the last statement to
"if l != []: cols = len(l[0])", you'll get in trouble if it
turns out that l = (). The uncluttered code will still work.

Secondly, if you ever write logical expressions that are more
complex, you will make them much more difficult to read unless
you drop that "== True" baggage.

I'm convinced that it's easier to understand

if past_six or past_three and saturday or sunday:

than to understand

if (past_six==True or
past_three==True and saturday==True or
sunday==True):

I'm also pretty sure it's easier to write the first without
making any mistake.
 
M

Michael Hoffman

Remi said:
I wrote it this way because, first, it's perfectly valid Python code and,
> second and most important, it's also a valid english sentence.

As others have pointed out, it's not perfectly valid code. In fact it is
frequently incorrect.
[CENSORED] I keep for myself how stupid I found your post...
Don't try to teach your grandfather how to suck eggs.

You apparently don't know how to do it without getting egg on your face.
 
J

Jeff Epler

def until(pred):
yield None
while True:
if pred(): break
yield None

def example():
i = 0
for _ in until(lambda: x==0):
x = 10 - i
i += 1
print x, i

example()

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFCuZa4Jd01MZaTXX0RAobdAJ93y6PxHS7oinElXZiBSXQMA6VWoQCfaV/C
C7D/7lDsUiHBWmRZ56Yhx3g=
=q/5k
-----END PGP SIGNATURE-----
 
S

Scott David Daniels

Magnus said:
In some cases, "==" and "is" happens to give the same result.
1

But often not.

....
First of all, a lot of Python values except 1 (a.k.a. True)
are logically true in a Python expression....

Actually, True and 1 are interesting examples.
False


I suspect you simply forgot this fact.

--Scott David Daniels
(e-mail address removed)
 
M

Michael Hoffman

Stelios said:
Magnus Lycka wrote:
>

Actually, there is support in marshal to write True and False objects so
I don't understand why this isn't in 2.4

Because it would break existing code.
 
A

Antoon Pardon

Op 2005-06-22 said:
As others have pointed out, it's not perfectly valid code. In fact it is
frequently incorrect.

That the same code would be incorrect in other circumstances doesn't
make it invalid as it was used in a specific situation.

I have written code my self with an "if var is True" statement and
that is exactly what I wanted. Replacing it with "if var" would
have broken the the program.
 
M

Mike Meyer

Stelios Xanthakis said:
Yes. Code that has variables named 'True' and 'False'.

Making None a constant broke existing code (and I just saw old code
that assigned to None). Are True and False that much more common as
variable names than None?

<mike
 
B

Benji York

Mike said:
Making None a constant broke existing code (and I just saw old code
that assigned to None). Are True and False that much more common as
variable names than None?

I would think so. I know that my pre-booleans-in-Python code routinely
did something like "from booleans import True, False". Of course the
fix is easy, but it still must be applied before the code will run.
 
M

Michael Hoffman

Mike said:
Making None a constant broke existing code (and I just saw old code
that assigned to None). Are True and False that much more common as
variable names than None?

Yes. In fact, I count at least 4 different modules in the Python 2.4
standard library that assign to True or False, mainly as a
compatibility measure for the days before they were built-ins. If you
try assigning None, CPython will refuse to compile the module, even if
the code where None is assigned is unreachable.

If there was ever a good reason to assign to None, I don't know it.
 
M

Michael Hoffman

Antoon said:
That the same code would be incorrect in other circumstances doesn't
make it invalid as it was used in a specific situation.

I have written code my self with an "if var is True" statement and
that is exactly what I wanted. Replacing it with "if var" would
have broken the the program.

That point was not lost on me (which is why I said it was frequently
incorrect). I think it was lost on the OP though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top