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

Jeff Epler jepler at unpythonic.net
Tue May 28 16:52:03 EDT 2002


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):
	...

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...

Jeff Epler
jepler at unpythonic.net

def G(v):
    if not v: return ()
    return (v,)

def H(f):
    while 1:
	v = f()
	if not v: break
	yield v





More information about the Python-list mailing list