Python: returns default value if function or expression fails

Does Python have a function that allows a function or expression to be evaluated, and if the evaluation fails (an exception is thrown), return the default.

Pseudo-code: evaluator(function/expression, default_value)

evaluator

will try to execute a function or expression and return a result if successful, otherwise it returns default_value

.

I know I am creating a custom function with try

and except

to achieve this, but I want to know if the batteries are included before I go and build my own solution.

+3


source to share


2 answers


No, the standard way to do this is try... except

.

There is no mechanism to hide or suppress any generic exception within a function. I suspect that many Python users would consider indiscriminate use of such a feature as non-Python for several reasons:

  • It hides information about what kind of exception occurred. (You might not want to handle all exceptions, as some of them may come from other libraries and specify conditions that your program cannot recover from, for example, due to insufficient disk space.)

  • It hides the fact that the exception happened at all; the default value returned in the event of an exception can be the same as a valid value other than the default. (Sometimes it is reasonable, sometimes it is not.)



One of the tenets of Python's philosophy, I believe, is that "explicit is better than implicit", so Python usually avoids automatic type selection and error recovery, which are features of more "implicit-friendly" languages ​​like Perl.

While the form try... except

can be a little verbose, in my opinion it has many advantages in terms of clearly showing where an exception might occur and what the flow of control is around that exception.

+2


source


To reuse your code, you can create a decorate function (which takes the default) and decorate your functions:

def handle_exceptions(default):
    def wrap(f):
        def inner(*a):
            try:
                return f(*a)
            except Exception, e:
                return default
        return inner
    return wrap

      



Now let's see an example:

@handle_exceptions("Invalid Argument")
def test(num):
    return 15/num

@handle_exceptions("Input should be Strings only!")
def test2(s1, s2):
    return s2 in s1    

print test(0) # "Invalid Argument"
print test(15) # 1

print test2("abc", "b") # True
print test2("abc", 1) # Input should be Strings only!

      

+5


source







All Articles