New (?) suggestion re: 'while x = f(): ...'

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed May 29 05:10:59 EDT 2002


Jeff Epler <jepler at unpythonic.net> wrote in 
news:mailman.1022619227.16027.python-list at python.org:

> and instead of
>     while 1:
>      x = f()
>      if not x: break
>      ...
> you can write
>     for x in H(f):
>      ...
> 
> Given suitable names for G() and H() (and I haven't thought of any yet)
> does anybody favor this over the "pythonic" syntax?  Personally, I think
> I'll stick to doing it in the old-fashioned way, but I wanted to share
> my idea with the world...

'H' is spelled 'iter' and already exists.
>>> f = open('afile.txt').readline
>>> while 1:
	x = f()
	if not x: break
	print x

is equivalent to:
>>> f = open('afile.txt').readline
>>> for x in iter(f, ""):
	print x

The second argument to iter as used here is the returned value that causes 
the loop to exit.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list