while loop with the condition used in the body

Peter Otten __peter__ at web.de
Wed Feb 24 05:21:36 EST 2010


Ulrich Eckhardt wrote:

> I'm looking for a way to write code similar to this C code:
> 
>   while(rq = get_request(..)) {
>      handle_request(rq);
>   }
> 
> Currently I'm doing
> 
>   while True:
>       rq = get_request(...)
>       if not rq:
>           break
>       handle_request(rq)
> 
> in Python 2.6. Any suggestions how to rewrite that?

Assuming get_request(...) is called with the same arguments on each 
iteration and uses None to signal that there is no more data:

from functools import partial

for rq in iter(partial(get_request, ...), None):
    handle_request(rq)

Peter



More information about the Python-list mailing list