newbie question...
Alex Martelli
alex at magenta.com
Wed Dec 29 16:39:36 EST 1999
Eugene Goodrich writes:
> I don't know why I tend to shy away from the while (1): in what I
> consider "simple" cases. I use it plenty in larger loops.
I do know why _I_ try hard to avoid it -- it's *ugly*!=)
Yep, I _am_ used to having to trot out the C/C++ equivalent:
for(;;) ...
or
while(1) ...
(I prefer the former, btw) -- oh btw, you don't need those
parentheses in Python:
while 1:
will do just as well -- but often in C++ I can have
while(!finished(nextitem = stepperfunc())) {
// ...
rather than the more spread-out
while(1) {
nextitem = stepperfunc();
if(finished(nextitem)) break;
// ...
and, since Python is mostly higher-level that C++,
it rankles to have to resort more often to a lower
level, more roundabout expression of the concept.
I'm more and more happy with the wrapped version:
for nextitem in enum(stepperfunc, finished):
with the enum wrapper I posted recently -- now my
mission in life is to make this a _common_ Python
idiom so people will start recognizing it!-)
> My inclusion of unnecessary parameters in some places comes from not
> always knowing the defaults and a desire to help out some of the less
> clueless readers of my code - like me 60 days after I write it :)
...and who says it's a bad practice...? Unnecessary _parentheses_ otoh
mark the newbie out (me just as well as you, of course:-).
> Thanks for the clue to use while (1) on the file reading. Jeez, I
> can't believe I've been using that lame prep code for so long. Gotta
> lay off the crack.
The repeated-stepping idiom you used:
nextitem = stepper()
while nextitem:
process(nextitem)
nextitem = stepper()
is actually best-practice in languages wich refuse to have
a 'break' statement (as well as assigning-expressions),
such as standard Pascal. And, to me:
while 1:
nextitem = stepper
if not nextitem:
break
process(nextitem)
is no big improvement -- one line longer (and Pythonistas
do seem to frown on the one-line form of if/break) and
less direct to boot.
for nextitem in enum(stepper):
process(nextitem)
now THAT is progress -- and, for this simple case,
class enum:
def __init__(self,stepper):
self.stepper=stepper
def __getitem__(self,key):
nextitem=self.stepper()
if not nextitem:
raise IndexError
return nextitem
is all the wrapper you need... buy now, while supplies
last!-)
Alex
More information about the Python-list
mailing list