[Python-ideas] "while ... try" - block or "for ... try" - block

Manuel Bärenz manuel at enigmage.de
Wed Jan 11 16:08:20 CET 2012


I propose two new control flows for Python:

"while ... try":

while expr try:
    suite1
except SomeException:
    suite2
else:
    suite3

This executes suite1 as long as handled exceptions are thrown and expr
is True.
* If an unhandled exception is thrown, it passes the exception on to the
surrounding or the stack.
* If no exception occurs, life goes on as normal, suite3 is executed and
execution goes on afterwards.

The control flow is thus equivalent to:

while expr:
    try:
        suite1
    except SomeException:
        suite2
    else:
        suite3
        break

But it's neater, very natural (in my opinion) and saves an indentation
level.

One further enhancement: If expr is encountered to be False, some
special exception "NoMoreTriesException" could be raised. It can be
catched in the same "while ... try" block.

Usecase:

while network_is_up() try:
    connect_to_server()
except ConnectError:
    time.sleep(timeout)
except NoMoreTriesException:
    print("Couldn't establish connection")
else:
    download_stuff()
finally:
    make_sure_resource_is_freed()

Another usecase:

while receive_packet() try:
    check_packet()
except ChecksumError:
    print("You sent the wrong thing. Try again.")
except NoMoreTriesException:
    print("I couldn't get a single useful packet from you :(")
else:
    process_packet()
finally:
    close_connection()


A similar thing could be made with "for ... try":

for password in passwords_i_remember try:
    connect(password)
except WrongPassError:
    pass # No pun intended
except NoMoreTriesException:
    print("Not a single one worked.")
else:
    check_mailbox()

The advantages are the same as for "while ... try".

Cheers, Manuel



More information about the Python-ideas mailing list