Artur Artur - 1 year ago 73
Python Question

Is creating a variable in try/except block considered a bad practice?

Let's consider this example - code that returns index of the first

None
value in the list
li
(if present) or the last element's index if
None
is not present in
li
.

I could possibly check for None being in list but using ifs isn't the preferred way - Dive Into Python encourages to use exceptions as they are said to be faster and make code cleaner (see this question). So I came with three approaches:

1.

try:
my_index = li.index(None)
except ValueError:
my_index = len(li) - 1

print my_index


my_index
is declared inside try/except block. Less lines, no redundant declaration. Possible problem - different exception type will result in not creating
my_index
and crashing the script on
print
.

2.

my_index = None # or anything else
try:
my_index = li.index(None)
except ValueError:
my_index = len(li) - 1

print my_index


my_index
is declared before try/except and has a value assigned regardless of what exception happens. Cons - more lines, looks redundant.

3. edit: Won't work - finally is executed regardless of try/except results

try:
my_index = li.index(None)
except ValueError:
my_index = len(li) - 1
finally:
my_index = None # or anything else

print my_index



Pros - always works (or at least I think so). Cons - I have never ever seen anyone using
finally
for my entire Python experience which must happen for a reason.

Which of these methods is considered the preferred and pythonic way? Maybe there is some better solution?

Answer Source
try:
    my_index = li.index(None)
except ValueError:
    my_index = len(li) - 1

print my_index

Possible problem - different exception type will result in not creating my_index and crashing the script on print.

Err, no. If any other exception is raised, this entire block of code will be aborted as the exception bubbles up to the caller. So if any other exception type besides ValueError is raised, print will never be executed. Which is a pretty sane behaviour: you handle the errors you expect and can handle, and let other errors cause the entire block to abort, possibly the entire script. This is the sanest and most concise solution for what you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download