while loop with the condition used in the body

Duncan Booth duncan.booth at invalid.invalid
Wed Feb 24 11:31:48 CET 2010

Peter Otten <__peter__ at web.de> wrote:

> Ulrich Eckhardt wrote:
>> I'm looking for a way to write code similar to this C code:
>>   while(rq = get_request(..)) {
>>      handle_request(rq);
>>   }
> 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

and the next step on from this is to realise that the problem isn't how to 
code the calls to get_request(), the problem is actually that get_request() 
itself isn'ty Pythonic. Rewrite it as a generator, rename it to reflect 
that it now generates a sequence of requests and the code becomes:

for rq in incoming_requests(...):

Duncan Booth http://kupuguy.blogspot.com

More information about the Python-list mailing list