Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #19190 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2012-01-22 01:59 +1100 |
| Last post | 2012-01-24 03:37 +0000 |
| Articles | 20 — 14 participants |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: while True or while 1 Chris Angelico <rosuav@gmail.com> - 2012-01-22 01:59 +1100
Re: while True or while 1 Erik Max Francis <max@alcyone.com> - 2012-01-21 13:13 -0800
Re: while True or while 1 Chris Angelico <rosuav@gmail.com> - 2012-01-22 09:13 +1100
Re: while True or while 1 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-01-22 05:25 +0000
Re: while True or while 1 Dan Sommers <dan@tombstonezero.net> - 2012-01-22 16:05 +0000
Re: while True or while 1 alex23 <wuwei23@gmail.com> - 2012-01-22 19:55 -0800
Re: while True or while 1 Dave Angel <d@davea.name> - 2012-01-23 08:02 -0500
Re: while True or while 1 Hrvoje Niksic <hniksic@xemacs.org> - 2012-01-23 14:28 +0100
Re: while True or while 1 Dave Angel <d@davea.name> - 2012-01-23 13:33 -0500
Re: while True or while 1 MRAB <python@mrabarnett.plus.com> - 2012-01-22 16:13 +0000
Re: while True or while 1 Grant Edwards <invalid@invalid.invalid> - 2012-01-23 15:51 +0000
Re: while True or while 1 Giampaolo Rodolà <g.rodola@gmail.com> - 2012-01-23 17:41 +0100
Re: while True or while 1 Erik Max Francis <max@alcyone.com> - 2012-01-23 11:12 -0800
Re: while True or while 1 Giampaolo Rodolà <g.rodola@gmail.com> - 2012-01-23 21:20 +0100
Re: while True or while 1 Ian Kelly <ian.g.kelly@gmail.com> - 2012-01-23 10:39 -0700
Re: while True or while 1 Evan Driscoll <edriscoll@wisc.edu> - 2012-01-23 12:05 -0600
Re: while True or while 1 Andrea Crotti <andrea.crotti.0@gmail.com> - 2012-01-23 20:50 +0000
Re: while True or while 1 88888 Dihedral <dihedral88888@googlemail.com> - 2012-01-23 14:42 -0800
Re: while True or while 1 88888 Dihedral <dihedral88888@googlemail.com> - 2012-01-23 14:42 -0800
Re: while True or while 1 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-01-24 03:37 +0000
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2012-01-22 01:59 +1100 |
| Subject | Re: while True or while 1 |
| Message-ID | <mailman.4909.1327157944.27778.python-list@python.org> |
On Sun, Jan 22, 2012 at 12:47 AM, Andrea Crotti <andrea.crotti.0@gmail.com> wrote: > So I tried to do the following, and the result is surprising. For what > I can see it looks like the interpreter can optimize away the 1 boolean > conversion while it doesn't with the True, the opposite of what I > supposed. > > Anyone can explain me why is that, or maybe is my conclusion wrong? In Python 3, they compile to the same code, because 'True' is a keyword. In Python 2, you can reassign True to be 0. ChrisA
[toc] | [next] | [standalone]
| From | Erik Max Francis <max@alcyone.com> |
|---|---|
| Date | 2012-01-21 13:13 -0800 |
| Message-ID | <pL-dnUjq2eH3t4bSnZ2dnUVZ5vudnZ2d@giganews.com> |
| In reply to | #19190 |
Chris Angelico wrote:
> On Sun, Jan 22, 2012 at 12:47 AM, Andrea Crotti
> <andrea.crotti.0@gmail.com> wrote:
>> So I tried to do the following, and the result is surprising. For what
>> I can see it looks like the interpreter can optimize away the 1 boolean
>> conversion while it doesn't with the True, the opposite of what I
>> supposed.
>>
>> Anyone can explain me why is that, or maybe is my conclusion wrong?
>
> In Python 3, they compile to the same code, because 'True' is a
> keyword. In Python 2, you can reassign True to be 0.
Why this should concern anyone, I don't know; someone who's rebound
`True` or `False` to evaluate to something other than true and false,
respectively, is only doing so to be difficult (or very foolish). One
of the principles of Python programming is that We're All Adults Here,
so this kind of defensive programming is really superfluous. In other
words, yes, it's quite reasonable to assume that (even in Python 2)
`True` is bound to something which is, in fact, true.
The real reason people still use the `while 1` construct, I would
imagine, is just inertia or habit, rather than a conscious, defensive
decision. If it's the latter, it's a case of being _way_ too defensive.
--
Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Jabber erikmaxfrancis
Ambition can creep as well as soar.
-- Edmund Burke
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2012-01-22 09:13 +1100 |
| Message-ID | <mailman.4914.1327184007.27778.python-list@python.org> |
| In reply to | #19194 |
On Sun, Jan 22, 2012 at 8:13 AM, Erik Max Francis <max@alcyone.com> wrote: > Why this should concern anyone, I don't know; someone who's rebound `True` > or `False` to evaluate to something other than true and false, respectively, > is only doing so to be difficult (or very foolish). One of the principles > of Python programming is that We're All Adults Here, so this kind of > defensive programming is really superfluous. In other words, yes, it's > quite reasonable to assume that (even in Python 2) `True` is bound to > something which is, in fact, true. Yes, but there's no special code in the compiler to handle True - it's just a name like any other. It finds a token that looks like a name, so it puts a name lookup into the bytecode. > The real reason people still use the `while 1` construct, I would imagine, > is just inertia or habit, rather than a conscious, defensive decision. If > it's the latter, it's a case of being _way_ too defensive. Ehh, 'while 1' is shorter too. I reckon some people are just lazy :) Or have come from C where 'while (1)' is the normal thing to do. According to the Eliza Effect, supporting 'while 1' is a Good Thing. ChrisA
[toc] | [prev] | [next] | [standalone]
| From | Steven D'Aprano <steve+comp.lang.python@pearwood.info> |
|---|---|
| Date | 2012-01-22 05:25 +0000 |
| Message-ID | <4f1b9dc4$0$29987$c3e8da3$5496439d@news.astraweb.com> |
| In reply to | #19196 |
On Sun, 22 Jan 2012 09:13:23 +1100, Chris Angelico wrote:
> On Sun, Jan 22, 2012 at 8:13 AM, Erik Max Francis <max@alcyone.com>
> wrote:
>> Why this should concern anyone, I don't know; someone who's rebound
>> `True` or `False` to evaluate to something other than true and false,
>> respectively, is only doing so to be difficult (or very foolish). One
>> of the principles of Python programming is that We're All Adults Here,
>> so this kind of defensive programming is really superfluous. In other
>> words, yes, it's quite reasonable to assume that (even in Python 2)
>> `True` is bound to something which is, in fact, true.
>
> Yes, but there's no special code in the compiler to handle True - it's
> just a name like any other. It finds a token that looks like a name, so
> it puts a name lookup into the bytecode.
>
>> The real reason people still use the `while 1` construct, I would
>> imagine, is just inertia or habit, rather than a conscious, defensive
>> decision. If it's the latter, it's a case of being _way_ too
>> defensive.
>
> Ehh, 'while 1' is shorter too. I reckon some people are just lazy :)
Or they've been writing Python code since before version 2.2 when True
and False were introduced, and so they are used to the "while 1" idiom
and never lost the habit.
In Python 2, "while 1" is a micro-optimization over "while True", because
there is no need to look-up the name True. For extremely tight loops,
that may make a difference.
In Python 3, there is no longer any real difference:
py> dis(compile('while 1: pass', '', 'exec'))
1 0 SETUP_LOOP 3 (to 6)
>> 3 JUMP_ABSOLUTE 3
>> 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
py> dis(compile('while True: pass', '', 'exec'))
1 0 SETUP_LOOP 3 (to 6)
>> 3 JUMP_ABSOLUTE 3
>> 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
Or perhaps they just like the look of "while 1".
--
Steven
[toc] | [prev] | [next] | [standalone]
| From | Dan Sommers <dan@tombstonezero.net> |
|---|---|
| Date | 2012-01-22 16:05 +0000 |
| Message-ID | <mailman.4925.1327248367.27778.python-list@python.org> |
| In reply to | #19203 |
On Sun, 22 Jan 2012 05:25:25 +0000, Steven D'Aprano wrote:
> Or they've been writing Python code since before version 2.2 when True
> and False were introduced, and so they are used to the "while 1" idiom
> and never lost the habit.
That would be me.
As per a now-ancient suggestion on this mailing list (I believe it was by
Tim Peters), I've also been known to use a non-empty, literal Python
string as a self-documenting, forever-True value in the typical loop-and-a-
half cnstruct:
while "the temperature is too big":
temperature = get_temperature()
if temperature <= threshold:
break
process_temperature(temperature)
This way, even though the loop condition is buried inside the loop (which
could be longer than four lines), it is apparent as soon as I encounter
the loop.
With the advent of the "with" statement, though, these loops are slowly
disappearing.
--
Dan
[toc] | [prev] | [next] | [standalone]
| From | alex23 <wuwei23@gmail.com> |
|---|---|
| Date | 2012-01-22 19:55 -0800 |
| Message-ID | <70a86eec-8fb5-477b-9797-e1f8af373b8e@nf9g2000pbc.googlegroups.com> |
| In reply to | #19217 |
On Jan 23, 2:05 am, Dan Sommers <d...@tombstonezero.net> wrote: > As per a now-ancient suggestion on this mailing list (I believe it was by > Tim Peters), I've also been known to use a non-empty, literal Python > string as a self-documenting, forever-True value in the typical loop-and-a- > half cnstruct: > > while "the temperature is too big": I don't think I've ever encountered this before, but I like it :) Cheers!
[toc] | [prev] | [next] | [standalone]
| From | Dave Angel <d@davea.name> |
|---|---|
| Date | 2012-01-23 08:02 -0500 |
| Message-ID | <mailman.4962.1327323756.27778.python-list@python.org> |
| In reply to | #19248 |
On 01/22/2012 10:55 PM, alex23 wrote:
> On Jan 23, 2:05 am, Dan Sommers<d...@tombstonezero.net> wrote:
>> As per a now-ancient suggestion on this mailing list (I believe it was by
>> Tim Peters), I've also been known to use a non-empty, literal Python
>> string as a self-documenting, forever-True value in the typical loop-and-a-
>> half cnstruct:
>>
>> while "the temperature is too big":
> I don't think I've ever encountered this before, but I like it :)
> Cheers!
I do something similar when there's a portion of code that should never
be reached:
assert("reason why I cannot get here")
--
DaveA
[toc] | [prev] | [next] | [standalone]
| From | Hrvoje Niksic <hniksic@xemacs.org> |
|---|---|
| Date | 2012-01-23 14:28 +0100 |
| Message-ID | <87lioyk0pi.fsf@xemacs.org> |
| In reply to | #19260 |
Dave Angel <d@davea.name> writes:
> I do something similar when there's a portion of code that should
> never be reached:
>
> assert("reason why I cannot get here")
Shouldn't that be assert False, "reason why I cannot get here"?
[toc] | [prev] | [next] | [standalone]
| From | Dave Angel <d@davea.name> |
|---|---|
| Date | 2012-01-23 13:33 -0500 |
| Message-ID | <mailman.4970.1327343648.27778.python-list@python.org> |
| In reply to | #19262 |
On 01/23/2012 08:28 AM, Hrvoje Niksic wrote:
> Dave Angel<d@davea.name> writes:
>
>> I do something similar when there's a portion of code that should
>> never be reached:
>>
>> assert("reason why I cannot get here")
> Shouldn't that be assert False, "reason why I cannot get here"?
You caught me in a typo. If it's in python there should be a not there,
and if it's in C, a bang.
--
DaveA
[toc] | [prev] | [next] | [standalone]
| From | MRAB <python@mrabarnett.plus.com> |
|---|---|
| Date | 2012-01-22 16:13 +0000 |
| Message-ID | <mailman.4927.1327248802.27778.python-list@python.org> |
| In reply to | #19203 |
On 22/01/2012 16:05, Dan Sommers wrote: > On Sun, 22 Jan 2012 05:25:25 +0000, Steven D'Aprano wrote: > >> Or they've been writing Python code since before version 2.2 when True >> and False were introduced, and so they are used to the "while 1" idiom >> and never lost the habit. > > That would be me. > > As per a now-ancient suggestion on this mailing list (I believe it was by > Tim Peters), I've also been known to use a non-empty, literal Python > string as a self-documenting, forever-True value in the typical loop-and-a- > half cnstruct: > > while "the temperature is too big": > temperature = get_temperature() > if temperature<= threshold: > break > process_temperature(temperature) > > This way, even though the loop condition is buried inside the loop (which > could be longer than four lines), it is apparent as soon as I encounter > the loop. > And the output of "dis" shows that it's optimised to a forever loop. > With the advent of the "with" statement, though, these loops are slowly > disappearing. >
[toc] | [prev] | [next] | [standalone]
| From | Grant Edwards <invalid@invalid.invalid> |
|---|---|
| Date | 2012-01-23 15:51 +0000 |
| Message-ID | <jfjvm9$1vc$1@reader1.panix.com> |
| In reply to | #19194 |
On 2012-01-21, Erik Max Francis <max@alcyone.com> wrote:
> Chris Angelico wrote:
>> On Sun, Jan 22, 2012 at 12:47 AM, Andrea Crotti
>> <andrea.crotti.0@gmail.com> wrote:
>>> So I tried to do the following, and the result is surprising. For what
>>> I can see it looks like the interpreter can optimize away the 1 boolean
>>> conversion while it doesn't with the True, the opposite of what I
>>> supposed.
>>>
>>> Anyone can explain me why is that, or maybe is my conclusion wrong?
>>
>> In Python 3, they compile to the same code, because 'True' is a
>> keyword. In Python 2, you can reassign True to be 0.
>
> Why this should concern anyone, I don't know;
I don't think it does concern anybody (except the compiler, who treats
all identifiers the same).
[...]
> The real reason people still use the `while 1` construct, I would
> imagine, is just inertia or habit,
That's certain why I do it. It's left over from the days when C and
Python didn't have symbolic boolean "constants".
> rather than a conscious, defensive decision. If it's the latter,
> it's a case of being _way_ too defensive.
--
Grant Edwards grant.b.edwards Yow! Hmmm ... A hash-singer
at and a cross-eyed guy were
gmail.com SLEEPING on a deserted
island, when ...
[toc] | [prev] | [next] | [standalone]
| From | Giampaolo Rodolà <g.rodola@gmail.com> |
|---|---|
| Date | 2012-01-23 17:41 +0100 |
| Message-ID | <mailman.4967.1327336916.27778.python-list@python.org> |
| In reply to | #19194 |
Il 21 gennaio 2012 22:13, Erik Max Francis <max@alcyone.com> ha scritto:
> The real reason people still use the `while 1` construct, I would imagine,
> is just inertia or habit, rather than a conscious, defensive decision. If
> it's the latter, it's a case of being _way_ too defensive.
It's also because while 1 is faster:
import time
t = time.time()
x = 0
while 1:
x += 1
if x > 10000000:
break
print(time.time() - t)
while True: 1.41121292114
while 1: 1.07101011276
Most of the times tha't won't make any noticeable difference, but it's
also true that certain while loops are going to iterate milions of
times.
Think about receiving a 10 GB file by using a socket. You'd tipically
have something like this:
while 1:
chunk = sock.recv(1024):
if not chunk:
break
...
Now, that's a case where I (personally) want to explicitly use "while
1" instead of "while True".
--- Giampaolo
http://code.google.com/p/pyftpdlib/
http://code.google.com/p/psutil/
http://code.google.com/p/pysendfile/
[toc] | [prev] | [next] | [standalone]
| From | Erik Max Francis <max@alcyone.com> |
|---|---|
| Date | 2012-01-23 11:12 -0800 |
| Message-ID | <4v6dnYAfTu69LIDSnZ2dnUVZ5r6dnZ2d@giganews.com> |
| In reply to | #19269 |
Giampaolo Rodolà wrote:
> Il 21 gennaio 2012 22:13, Erik Max Francis <max@alcyone.com> ha scritto:
>> The real reason people still use the `while 1` construct, I would imagine,
>> is just inertia or habit, rather than a conscious, defensive decision. If
>> it's the latter, it's a case of being _way_ too defensive.
>
> It's also because while 1 is faster:
...
> while True: 1.41121292114
> while 1: 1.07101011276
>
> Most of the times tha't won't make any noticeable difference, but it's
> also true that certain while loops are going to iterate milions of
> times.
> Think about receiving a 10 GB file by using a socket. You'd tipically
> have something like this:
>
> while 1:
> chunk = sock.recv(1024):
> if not chunk:
> break
> ...
>
> Now, that's a case where I (personally) want to explicitly use "while
> 1" instead of "while True".
Such a loop would obviously be I/O-bound, not CPU-bound. So changing
the form of the while loop would make minimal difference to its overall
performance. It'd be spending the vast majority of its time blocked at
the OS socket level, not executing the condition of the while loop.
As with most of these things, if one is this worried about performance,
then either Python was the wrong choice to begin with, or there's a good
chance that you're worried about something that isn't actually where the
bottleneck is in the first place.
--
Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Jabber erikmaxfrancis
Think twice before you speak to a friend in need.
-- Ambrose Bierce
[toc] | [prev] | [next] | [standalone]
| From | Giampaolo Rodolà <g.rodola@gmail.com> |
|---|---|
| Date | 2012-01-23 21:20 +0100 |
| Message-ID | <mailman.4978.1327350029.27778.python-list@python.org> |
| In reply to | #19278 |
Il 23 gennaio 2012 20:12, Erik Max Francis <max@alcyone.com> ha scritto: > Giampaolo Rodolà wrote: >> >> Il 21 gennaio 2012 22:13, Erik Max Francis <max@alcyone.com> ha scritto: >>> >>> The real reason people still use the `while 1` construct, I would >>> imagine, >>> >>> is just inertia or habit, rather than a conscious, defensive decision. >>> If >>> it's the latter, it's a case of being _way_ too defensive. >> >> >> It's also because while 1 is faster: > > ... >> >> while True: 1.41121292114 >> while 1: 1.07101011276 >> >> Most of the times tha't won't make any noticeable difference, but it's >> also true that certain while loops are going to iterate milions of >> times. >> Think about receiving a 10 GB file by using a socket. You'd tipically >> have something like this: >> >> while 1: >> chunk = sock.recv(1024): >> if not chunk: >> break >> ... >> >> Now, that's a case where I (personally) want to explicitly use "while >> >> 1" instead of "while True". > > > Such a loop would obviously be I/O-bound, not CPU-bound. So changing the > form of the while loop would make minimal difference to its overall > performance. It'd be spending the vast majority of its time blocked at the > OS socket level, not executing the condition of the while loop. > > As with most of these things, if one is this worried about performance, then > either Python was the wrong choice to begin with, or there's a good chance > that you're worried about something that isn't actually where the bottleneck > is in the first place. > > > -- > Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Jabber erikmaxfrancis > Think twice before you speak to a friend in need. > -- Ambrose Bierce > -- > http://mail.python.org/mailman/listinfo/python-list Obviously, you're right. I picked up the wrong example. My point is 1.41121292114 vs 1.07101011276 *might* make some difference in certain cases. I just can't come up with a good example where that would be justified. =) --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ http://code.google.com/p/pysendfile/
[toc] | [prev] | [next] | [standalone]
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2012-01-23 10:39 -0700 |
| Message-ID | <mailman.4968.1327340413.27778.python-list@python.org> |
| In reply to | #19194 |
On Mon, Jan 23, 2012 at 9:41 AM, Giampaolo Rodolà <g.rodola@gmail.com> wrote: > > Il 21 gennaio 2012 22:13, Erik Max Francis <max@alcyone.com> ha scritto: > > The real reason people still use the `while 1` construct, I would imagine, > > is just inertia or habit, rather than a conscious, defensive decision. If > > it's the latter, it's a case of being _way_ too defensive. > > It's also because while 1 is faster: That's because, as has already been pointed out in the thread, the compiler is able to store the 1 literal with the code, whereas "True" requires a name lookup. If you try the same timing test in Python 3, you will find that there is no longer any difference. > Think about receiving a 10 GB file by using a socket. You'd tipically > have something like this: > > while 1: > chunk = sock.recv(1024): > if not chunk: > break > ... > > > Now, that's a case where I (personally) want to explicitly use "while > 1" instead of "while True". I disagree. 10 GB in 1 KB chunks is going to be 10,000,000 loops, which as you just demonstrated above, carries an overhead of about 0.4 seconds if we use True instead of 1. That's entirely trivial compared to the time needed to actually transfer the file. Moreover, unless you're doing a significant amount of processing on the file as you read it, a socket-reading loop like that is likely to be IO-bound -- which means that after the "while 1" check, the process is usually going to go to sleep anyway as it waits for more data. In that case, the extra 40 nanoseconds for the name lookup makes no difference at all, as the process wasn't going to do anything useful with those cycles anyway. Actually, I have a hard time envisioning a case where the difference between "while 1" and "while True" in Python 2.x is worth caring about. At the point where it might actually start to be noticeable (say around 100 million iterations), there are surely higher-priority optimizations to be made, including rewriting parts of the program in C. "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" -- Donald Knuth Cheers, Ian
[toc] | [prev] | [next] | [standalone]
| From | Evan Driscoll <edriscoll@wisc.edu> |
|---|---|
| Date | 2012-01-23 12:05 -0600 |
| Message-ID | <mailman.4972.1327345569.27778.python-list@python.org> |
| In reply to | #19194 |
On 01/23/2012 11:39 AM, Ian Kelly wrote: > "We should forget about small efficiencies, say about 97% of the time: > premature optimization is the root of all evil" > -- Donald Knuth To play devil's advocate for a moment, if you have the choice between two ways of writing something, A and B, where both are basically the same in terms of difficulty to write, difficulty to maintain, and difficulty to understand, but A is faster than B, even if just by a hair, why NOT write A? It's like 'iter++' vs '++iter' in a C++ for loop. For ints, or for some iterators with optimization, it makes no difference. But the latter will be faster in debug builds, and *might* be faster in release builds if you have a complicated iterator. So why NOT make for(...; ...; ++i) the typical way of writing a for loop? In the Python world, is 'while 1' any harder to understand than 'while True'? I'm about as staunch a supporter as you'll find for the idea that 'while 1' should throw an exception, and even *I* think that 'while 1' is about the least-offensive idiom out there. If 'while 1' throws you off, I'd hate to see what you do when you learn that Python accepts loops like 'while x' where the condition evaluates to true if x is a non-zero integer and false if x is 0. All that said, I like the 'while "stuff to do"' idea. Evan
[toc] | [prev] | [next] | [standalone]
| From | Andrea Crotti <andrea.crotti.0@gmail.com> |
|---|---|
| Date | 2012-01-23 20:50 +0000 |
| Message-ID | <mailman.4983.1327351819.27778.python-list@python.org> |
| In reply to | #19194 |
On 01/23/2012 06:05 PM, Evan Driscoll wrote: > > To play devil's advocate for a moment, if you have the choice between > two ways of writing something, A and B, where both are basically the > same in terms of difficulty to write, difficulty to maintain, and > difficulty to understand, but A is faster than B, even if just by a > hair, why NOT write A? > > It's like 'iter++' vs '++iter' in a C++ for loop. For ints, or for > some iterators with optimization, it makes no difference. But the > latter will be faster in debug builds, and *might* be faster in > release builds if you have a complicated iterator. So why NOT make > for(...; ...; ++i) the typical way of writing a for loop? > > In the Python world, is 'while 1' any harder to understand than 'while > True'? I'm about as staunch a supporter as you'll find for the idea > that 'while 1' should throw an exception, and even *I* think that > 'while 1' is about the least-offensive idiom out there. If 'while 1' > throws you off, I'd hate to see what you do when you learn that Python > accepts loops like 'while x' where the condition evaluates to true if > x is a non-zero integer and false if x is 0. > > > All that said, I like the 'while "stuff to do"' idea. > > Evan I think it's not the same, iter++ or ++iter is exactly the same in terms of readability, so of course if one might be a bit faster, it should be used. while 1 works because the 1 is converted to boolean automatically, but why not just writing a boolean in the first place? It's not bad of course but to me it's not very Pythonic, and reminds me C. At that point I also prefer the "while 'might be long loop'" idea, which at least adds some value *and* it might be very slightly faster too.
[toc] | [prev] | [next] | [standalone]
| From | 88888 Dihedral <dihedral88888@googlemail.com> |
|---|---|
| Date | 2012-01-23 14:42 -0800 |
| Message-ID | <mailman.4993.1327358527.27778.python-list@python.org> |
| In reply to | #19286 |
在 2012年1月24日星期二UTC+8上午4时50分11秒,Andrea Crotti写道: > On 01/23/2012 06:05 PM, Evan Driscoll wrote: > > > > To play devil's advocate for a moment, if you have the choice between > > two ways of writing something, A and B, where both are basically the > > same in terms of difficulty to write, difficulty to maintain, and > > difficulty to understand, but A is faster than B, even if just by a > > hair, why NOT write A? > > > > It's like 'iter++' vs '++iter' in a C++ for loop. For ints, or for > > some iterators with optimization, it makes no difference. But the > > latter will be faster in debug builds, and *might* be faster in > > release builds if you have a complicated iterator. So why NOT make > > for(...; ...; ++i) the typical way of writing a for loop? > > > > In the Python world, is 'while 1' any harder to understand than 'while > > True'? I'm about as staunch a supporter as you'll find for the idea > > that 'while 1' should throw an exception, and even *I* think that > > 'while 1' is about the least-offensive idiom out there. If 'while 1' > > throws you off, I'd hate to see what you do when you learn that Python > > accepts loops like 'while x' where the condition evaluates to true if > > x is a non-zero integer and false if x is 0. > > > > > > All that said, I like the 'while "stuff to do"' idea. > > > > Evan > > I think it's not the same, iter++ or ++iter is exactly the same in terms > of readability, so of course > if one might be a bit faster, it should be used. > > while 1 works because the 1 is converted to boolean automatically, but > why not just writing a boolean > in the first place? > > It's not bad of course but to me it's not very Pythonic, and reminds me C. > At that point I also prefer the "while 'might be long loop'" idea, which > at least > adds some value *and* it might be very slightly faster too. A fake generator that can't be cascaded for more processing can be called an iterator by the definition of an iterator. But that is miss-leading in implementing silly trivial non-qualified iterators.
[toc] | [prev] | [next] | [standalone]
| From | 88888 Dihedral <dihedral88888@googlemail.com> |
|---|---|
| Date | 2012-01-23 14:42 -0800 |
| Message-ID | <21560499.1074.1327358522792.JavaMail.geo-discussion-forums@prmu37> |
| In reply to | #19286 |
在 2012年1月24日星期二UTC+8上午4时50分11秒,Andrea Crotti写道: > On 01/23/2012 06:05 PM, Evan Driscoll wrote: > > > > To play devil's advocate for a moment, if you have the choice between > > two ways of writing something, A and B, where both are basically the > > same in terms of difficulty to write, difficulty to maintain, and > > difficulty to understand, but A is faster than B, even if just by a > > hair, why NOT write A? > > > > It's like 'iter++' vs '++iter' in a C++ for loop. For ints, or for > > some iterators with optimization, it makes no difference. But the > > latter will be faster in debug builds, and *might* be faster in > > release builds if you have a complicated iterator. So why NOT make > > for(...; ...; ++i) the typical way of writing a for loop? > > > > In the Python world, is 'while 1' any harder to understand than 'while > > True'? I'm about as staunch a supporter as you'll find for the idea > > that 'while 1' should throw an exception, and even *I* think that > > 'while 1' is about the least-offensive idiom out there. If 'while 1' > > throws you off, I'd hate to see what you do when you learn that Python > > accepts loops like 'while x' where the condition evaluates to true if > > x is a non-zero integer and false if x is 0. > > > > > > All that said, I like the 'while "stuff to do"' idea. > > > > Evan > > I think it's not the same, iter++ or ++iter is exactly the same in terms > of readability, so of course > if one might be a bit faster, it should be used. > > while 1 works because the 1 is converted to boolean automatically, but > why not just writing a boolean > in the first place? > > It's not bad of course but to me it's not very Pythonic, and reminds me C. > At that point I also prefer the "while 'might be long loop'" idea, which > at least > adds some value *and* it might be very slightly faster too. A fake generator that can't be cascaded for more processing can be called an iterator by the definition of an iterator. But that is miss-leading in implementing silly trivial non-qualified iterators.
[toc] | [prev] | [next] | [standalone]
| From | Steven D'Aprano <steve+comp.lang.python@pearwood.info> |
|---|---|
| Date | 2012-01-24 03:37 +0000 |
| Message-ID | <4f1e278a$0$11127$c3e8da3@news.astraweb.com> |
| In reply to | #19286 |
On Mon, 23 Jan 2012 20:50:11 +0000, Andrea Crotti wrote:
> while 1 works because the 1 is converted to boolean automatically, but
> why not just writing a boolean
> in the first place?
You have misunderstood Python's truth model. It is similar to languages
like Javascript and PHP, where EVERY object without exception has a truth
value.
Python does not convert 1 to a boolean, because that would be pointless
and silly. Bools True and False in Python are no more privileged than
anything else, in fact they are *less* privileged in Python 2 because
they are merely built-in names which can be re-bound, not reserved words
like None.
In Python 2, the peephole optimizer can optimize away constants such as
1. But 1 itself is not special -- any non-zero int, or non-empty string,
is also a true-ish value:
>>> from dis import dis
>>> dis(compile('if 42: spam', '', 'exec'))
1 0 LOAD_NAME 0 (spam)
3 POP_TOP
4 LOAD_CONST 0 (None)
7 RETURN_VALUE
While True is just a name, and therefore needs to be looked up at runtime
like every other name:
>>> dis(compile('if True: spam', '', 'exec'))
1 0 LOAD_NAME 0 (True)
3 JUMP_IF_FALSE 8 (to 14)
6 POP_TOP
7 LOAD_NAME 1 (spam)
10 POP_TOP
11 JUMP_FORWARD 1 (to 15)
>> 14 POP_TOP
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
In Python 3, True and False become constants, like None, and the peephole
optimizer can treat them like 42 or 0 or -3. Nevertheless, the important
factor is not the optimizer, but the JUMP_IF_FALSE op-code. That accepts
*any* Python object, not just True and False:
>>> dis(compile('if [1, 2, 3]: spam', '', 'exec'))
1 0 LOAD_CONST 0 (1)
3 LOAD_CONST 1 (2)
6 LOAD_CONST 2 (3)
9 BUILD_LIST 3
12 JUMP_IF_FALSE 8 (to 23)
15 POP_TOP
16 LOAD_NAME 0 (spam)
19 POP_TOP
20 JUMP_FORWARD 1 (to 24)
>> 23 POP_TOP
>> 24 LOAD_CONST 3 (None)
27 RETURN_VALUE
Note that a sufficiently clever peephole optimizer could have recognised
that [1,2,3] is a true value, just as 42 is a true value. But that's
besides the point: what is important is that any object is true-ish or
false-ish.
The only advantages to True and False are:
(1) They satisfy programmers from Pascal and other languages which insist
on actual Boolean types in comparisons.
You can recognise these people who haven't quite yet grasped Python's
model, and are still writing Pascal or Java, because they write unpythonic
code which does unnecessary work, such as "if bool(x)" instead of just
"if x". Worse are the ones who write "if bool(x) is True", because they
don't even understand boolean logic.
(2) They are self-documenting, especially for return values. If a
function returns 0 or 1, there may be some uncertainty whether that
should be understood as a number, or a flag. By returning False or True,
it self-documents that it is a flag.
(3) It avoids people having to define their own true/false values, with a
multitude of spellings, in every library and project that uses them.
If your branch (while loop or if/elif clause) is taking a constant
literal, you probably should prefer True/False over any other object
simply because it is more readable and clear as to your intention. But it
is no big deal if you prefer 1/0 instead.
If you branch over an arbitrary named object, like "while x", there is no
point in writing that as "while bool(x)". All that does is indicate that
you are uncomfortable with, or don't understand, Python's truth model,
and perform an extra, unnecessary, name lookup and function call.
--
Steven
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web