Why is "while" ticking me off???
Alex Martelli
aleaxit at yahoo.com
Fri Oct 6 05:50:44 EDT 2000
"Steve Lamb" <grey at despair.rpglink.com> wrote in message
news:slrn8tq8sp.aj6.grey at teleute.rpglink.com...
> On Thu, 05 Oct 2000 19:58:25 -0400, Thomas Gagne <tgagne at ix.netcom.com>
wrote:
> >while line = fp.readline():
> > do something with 'line'
>
> Perlism?
>
> >I'm obviously not approaching this in the Python idiomatic way.
>
> while 1:
> line = fp.readline()
> if not line:
> break
> do something with 'line'
Yes, this is canonical, but it's one of the few things I dislike
in Python. I much prefer a wrap-into-a-sequence approach -- I
have in my site.py this definition:
class lazyseq:
def __init__(self, func, termtest=None):
self.func=func
self.term=termtest
if not self.term:
self.term = lambda x, y: not x
def __getitem__(self, index):
item = self.func()
if self.term(item, index): raise IndexError
return item
which lets me do
for line in lazyseq(fp.readline):
do something with line
For a more general approach to introducing functional programming
idioms (laziness in particular) into Python, see functional.py at:
http://sourceforge.net/projects/xoltar-toolkit/
Alex
More information about the Python-list
mailing list