PEP-0315--Enhanced While Loop: An idea for an alternative syntax

Jeff Epler jepler at unpythonic.net
Wed Feb 18 20:10:06 EST 2004


On Wed, Feb 18, 2004 at 05:41:10PM +0000, Terry Carroll wrote:
> With read() instead of readline(), then.
> 
> I've certainly run into this using urllib2.

Push the "yucky" while 1: loop into a generator function,
and then use a regular "for" loop in the multiple places 
you need to handle a file in this way:

    def chunks(f, blocksize=512):
        while 1:
            b = f.read(blocksize)
            if not b: return
            yield b

Use it like this:
>>> f = open("/etc/fedora-release")
>>> for c in chunks(f, 4): print repr(c),
... 
'Fedo' 'ra C' 'ore ' 'rele' 'ase ' '1 (Y' 'arro' 'w)\n'

The "while 1:" loop is now so short that a simple glance can take it all
in, and the site with the logic uses the much clearer 'for' loop.

Jeff




More information about the Python-list mailing list