Python Success Stories or Nightmares

Andrew Bennetts andrew-pythonlist at puzzling.org
Sun Feb 2 21:34:30 EST 2003


On Sun, Feb 02, 2003 at 06:11:53PM -0800, Paul Rubin wrote:
> Alexander Schmolck <a.schmolck at gmx.net> writes:
> > Well, given that there simply *is* no reason to "miss that one-liner" you
> > mention above -- as it would just provide an idiotic way to write:
> > 
> >  for line in file:...           # doesn't need more RAM BTW
> > 
> > --  what did you expect?
> 
> How would you write
> 
>    while ((c = getc(file)) != EOF)
>        ...
> 
> without missing the one-liner?

The standard Python idiom for this is, of course:

    while 1:
        c = f.read(1)
        if not c:
            break
        ...

Which I think is much clearer, and not prone to errors if you muck up a
parenthesis or "="/"==".  And it's one less idiom you have to learn to read other
people's code, but if you've already learnt it, you probably don't care ;)

If you do this in Python alot, and really really want a one-liner, you could
do:

    def getc(f):
        while 1:
            c = f.read(1)
            if not c:
                return
            yield c

Which you could then use as:

    for c in getc(f):
        ...

That gives you the one-liner without all the punctuation.  Good enough?

-Andrew.






More information about the Python-list mailing list