I find myself having this sort of pattern over and over:
variable = ""
try:
variable = ... do some file loading stuff ...
except:
variable = ""
Is there any way to condense this into a single expression? Like with if-else statements you can turn:
variable = ""
if something:
variable = somethingelse
else:
variable = ""
into
variable = somethingelse if something else ""
Is there any equivalent thing for try-catch?
Since agf already provided the approach I’d recommend, here’s a version of his routine with a couple of minor enhancements:
This version:
Lets you specify exactly which exceptions will be caught as additional optional arguments. You should always catch the minimum set of exceptions that will do the job and let exceptions you can’t handle bubble up to the caller.
Supports the use of a plain value as well as a function for the failure value. This saves you having to use a lambda in a lot of cases. (Of course, instead of
lambda: ''you can just usestr.)