Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: try-except as an Expression?

Tags:

python

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?

like image 863
Li Haoyi Avatar asked Aug 17 '11 04:08

Li Haoyi


People also ask

How do you use try and except in a function in Python?

The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.

Does try-Except end function?

In Python, try and except are used to handle exceptions (= errors detected during execution). With try and except , even if an exception occurs, the process continues without terminating. You can use else and finally to set the ending process.

Is there an Except function in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.

How do I print error try-except in Python?

If you are going to print the exception, it is better to use print(repr(e)) ; the base Exception. __str__ implementation only returns the exception message, not the type. Or, use the traceback module, which has methods for printing the current exception, formatted, or the full traceback.


2 Answers

Since agf already provided the approach I'd recommend, here's a version of his routine with a couple of minor enhancements:

def try_except(success, failure, *exceptions):     try:         return success()     except exceptions or Exception:         return failure() if callable(failure) else failure 

This version:

  1. 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.

  2. 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 use str.)

like image 88
kindall Avatar answered Sep 24 '22 12:09

kindall


def try_except(success, failure):     try:         return success()     except:         return failure()  variable = try_except(do_some_file_loading_stuff, lambda: '') 

I think the code is self explanatory. It returns the value returned by success unless there is an error, then it returns the value returned by failure. If do_some_file_loading_stuff is an expression rather than just a function call, wrap it in a lambda as well.

Edit: @kindall and I improved his version a bit so it's just as fast as mine, can be called exactly the same if you want, has more features, and is the same number of lines. Use it!

def try_except(success, failure, *exceptions):     try:         return success()     except exceptions or Exception:         return failure() if callable(failure) else failure 
like image 23
agf Avatar answered Sep 21 '22 12:09

agf