while loop with the condition used in the body
Peter Otten
__peter__ at web.de
Wed Feb 24 05:38:33 EST 2010
Duncan Booth wrote:
> 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(...):
> handle_request(rq)
...and a likely implementation would be
def incoming_requests(...):
while True:
rq = ... # inlined version of get_request()
if not rq:
break
yield rq
In other words: It's turtles all the way down...
Peter
More information about the Python-list
mailing list