No "side effect" assignment!

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Sep 15 04:51:55 EDT 2003


Tobiah <toby at rcsreg.com> wrote in 
news:0fbc28ebd2ba4810db3efef3a29f990a at news.teranews.com:

> I can't seem to do this in python without gagging:
> 
> foo = getmore()
> while foo:
>      process(foo)
>      foo = getmore()
> 
> 
> Is that what ppl do?  

I don't know about ppl, but Python programmers have a variety of ways of 
structuring this code. The one that I think is simplest, but is often 
overlooked is to use the builtin function 'iter'. It won't exactly replace 
the code you have above, since your loop terminates as soon as getmore() 
returns anything false (None, 0, False, '' would all terminate it). If 
however you know the exact value to indicate termination (I'll guess 
getmore() returns None when its done), you can write your loop:

for foo in iter(getmore, None):
    process(foo)

If instead of a simple function call you had a more complex expression (say 
getmore took a file as an argument), you might consider a lambda:

for foo in iter(lambda: getmore(aFile), None):
    process(foo)


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