while loop with the condition used in the body

Discussion in 'Python' started by Ulrich Eckhardt, Feb 24, 2010.

  1. Hi!

    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?

    Uli
     
    Ulrich Eckhardt, Feb 24, 2010
    #1
    1. Advertisements

  2. This is the common idiom.
     
    Arnaud Delobelle, Feb 24, 2010
    #2
    1. Advertisements

  3. Ulrich Eckhardt

    Peter Otten Guest

    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
     
    Peter Otten, Feb 24, 2010
    #3
  4. Ulrich Eckhardt

    Peter Otten Guest

    ....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
     
    Peter Otten, Feb 24, 2010
    #4
  5. Almost. While it moves the ugliness, at least it allows separating the
    iteration logic from the handling logic, which is already a big step ahead!

    That said, there is:

    with <expression> as <name>:
    ...

    so why not:

    while <expression> as <name>:
    ...

    and also:

    if <expression> as <name>:
    ...


    Thanks to everybody for their input!

    Uli
     
    Ulrich Eckhardt, Feb 24, 2010
    #5
  6. This sort of thing has been suggested repeatedly in the
    past, and it's always been rejected. That's not likely to
    change. Look up the past threads for the reasons why.
     
    Gregory Ewing, Feb 25, 2010
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.