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

Delaney, Timothy tdelaney at avaya.com
Tue May 28 21:10:22 EDT 2002


> From: Jeff Epler [mailto:jepler at unpythonic.net]
> 
> Why not abuse the 'for' statement, since it performs an 
> assignment to a
> user-determined name?
> 
> Instead of 
>     x = v
>     if x:
> 	...
> you can write
>     for x in G(v):
> 	...
> 
> and instead of
>     while 1:
> 	x = f()
> 	if not x: break
> 	...
> you can write
>     for x in H(f):
> 	...

In fact this is not abuse - this is precisely the pythonic way. Especially
now that iterators and generators have been added to the language.

The classic case is

	while line = f.readline(): #illegal
	    print line

which *should* be replaced by

	for line in f.readlines():
	    print line

or

	for line in f.xreadlines():
	    print line

or

	for line in f:
	    print line

and if you want to filter out some of the lines (or break out of the loop
when reaching a certain line):

	def filterLines (f):
	    for line in f:
	        if line:
	            yield line

	for line in filterLines(f):
	    print line

Now, it may be that your function only returns a single value - fine. It's
still Pythonic.

Tim Delaney





More information about the Python-list mailing list