Consider this line:
some_value = lst.attr[idx]
There are two possible errors here, the attr might not exist, and the idx might be out of range.
Is there any elegant way to reduce this statement? Ideally, to something like this:
some_value = lst.attr[idx] or default_value
(Don’t try that at home. That only works for properly defined expressions that evaluate to something.)
Sure I can do:
try:
some_value = lst.attr[idx]
except:
some_value = default_value
But what if I’m in the context of an assignment? For example:
print [x.attr[idx] for x in y]
What’s the pythonic way to handle errors and assign default values in this case?
You need to decide what you are trying achieve here. The use of the word “error” is probably misleading.
If you are actually trying to handle the case where the wrong type of object is passed to your function then you don’t want to handle that and should raise an exception.
If you are trying to allow your function to be used on a series of different types then that’s not really an error and using a default value may be reasonable.
The simplest option is to test whether the attribute exists first. For example:
I’m assuming the
lst.attris a dictionary, in which case you can handle the default value like so:Never use a
try/exceptstatement where you don’t specify what exception you are catching. You can end up masking much more than you intended to.With your final piece of code I think you should not try and solve it in a single line. Readability counts. I’m not happy with the code below, but it would be improved if
x,yandattrwere replaced with more descriptive names.