[Python-ideas] "while ... try" - block or "for ... try" - block
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:
This executes suite1 as long as handled exceptions are thrown and expr
* 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:
But it's neater, very natural (in my opinion) and saves an indentation
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.
while network_is_up() try:
print("Couldn't establish connection")
while receive_packet() try:
print("You sent the wrong thing. Try again.")
print("I couldn't get a single useful packet from you :(")
A similar thing could be made with "for ... try":
for password in passwords_i_remember try:
pass # No pun intended
print("Not a single one worked.")
The advantages are the same as for "while ... try".
More information about the Python-ideas