Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat something upon exception in python?

What is the most elegant way to repeat something after it caused an exception in python?

I have something like this [pseudo code as an example]:

try:
  do_some_database_stuff()
except DatabaseTimeoutException:
  reconnect_to_database()
  do_some_database_stuff() # just do it again

But imagine if I don't have a nice function but a lot of code instead. Duplicate code is not very nice.

So I think this is slightly better:

while True:
  try:
    do_some_database_stuff()
    break
  except DatabaseTimeoutException:
    reconnect_to_database()

That's good enough if the exception really fixes the problem. If not I need a counter to prevent an indefinite loop:

i = 0
while i < 5:
  try:
    do_some_database_stuff()
    break
  except DatabaseTimeoutException:
    reconnect_to_database()
    i += 1

But then I don't really know if it worked so it's also:

while i <= 5:
  try:
    do_some_database_stuff()
    break
  except DatabaseTimeoutException:
    if i != 5:
     reconnect_to_database()
    else:
      raise DatabaseTimeoutException
    i += 1

As you can see it starts to get very messy.

What is the most elegant way of expressing this logic?

  • try something
  • if it fails apply fix
  • try n more times including the fix
  • if it continues to fail give me an error to prevent a indefinite loop
like image 656
JasonTS Avatar asked Nov 07 '14 04:11

JasonTS


1 Answers

You can use a "for-else" loop:

for ii in range(5):
    try:
        do_some_database_stuff()
        break
    except DatabaseTimeoutException:
        reconnect_to_database()
else:
    raise DatabaseTimeoutException

Or, without:

for ii in range(5):
    try:
        do_some_database_stuff()
        break
    except DatabaseTimeoutException:
        if ii == 4:
            raise
        reconnect_to_database()
like image 74
John Zwinck Avatar answered Sep 24 '22 19:09

John Zwinck