I know what a try-else
block is, but consider the following two functions:
# Without else
def number_of_foos1(x):
try:
number = x['foo_count']
except:
return 0
return number
# With else
def number_of_foos2(x):
try:
number = x['foo_count']
except:
return 0
else:
return number
x_with_foo = dict(foo_count=5)
x_without_foo = 3
Unlike this try-else
question we're not adding extra lines to the try
block. In both cases the try
block is a single line, and the principle of keeping error handling "close" to the errors that caused it is not violated.
The difference is in where we go after the successful try
block.
In the first block, the code continues after the except
block, and in the second, the code continues at the else
.
They obviously give the same output:
In [138]: number_of_foos1(x_with_foo)
Out[139]: 5
In [140]: number_of_foos1(x_without_foo)
Out[140]: 0
In [141]: number_of_foos2(x_with_foo)
Out[141]: 5
In [142]: number_of_foos2(x_without_foo)
Out[142]: 0
Is either preferred? Are they even any different as far as the interpreter is concerned? Should you always have an else
when continuing after a successful try
or is it OK just to carry on unindented, as in number_of_foos1
?