Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: return a default value if function or expression fails

Does Python has a feature that allows one to evaluate a function or expression and if the evaluation fails (an exception is raised) return a default value.

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

The evaluator will try to execute the function or expression and return the result is the execution is successful, otherwise the default_value is returned.

I know I create a user defined function using try and except to achieve this but I want to know if the batteries are already included before going off and creating a custom solution.

like image 319
mattgathu Avatar asked Sep 15 '14 06:09

mattgathu


People also ask

How do you return a default value in Python?

A Python function will always have a return value. There is no notion of procedure or routine in Python. So, if you don't explicitly use a return value in a return statement, or if you totally omit the return statement, then Python will implicitly return a default value for you.

How will you specify a default value for an argument in the function definition?

Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

How do you return nothing from a function in Python?

If you want to return a null function in Python then use the None keyword in the returns statement. Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing').

What is default argument function in Python?

Default arguments in Python functions are those arguments that take default values if no explicit values are passed to these arguments from the function call. Let's define a function with one default argument. def find_square(integer1=2): result = integer1 * integer1 return result.


2 Answers

In order to reuse code, you can create a decorating function (that accepts a default value) and decorate your functions with it:

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!
like image 90
Nir Alfasi Avatar answered Nov 03 '22 00:11

Nir Alfasi


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

There is no mechanism to hide or suppress any generic exception within a function. I suspect many Python users would consider indiscriminate use of such a function to be un-Pythonic for a couple reasons:

  1. It hides information about what particular exception occurred. (You might not want to handle all exceptions, since some could come from other libraries and indicate conditions that your program can't recover from, like running out of disk space.)

  2. It hides the fact that an exception occurred at all; the default value returned in case of an exception might coincide with a valid non-default value. (Sometimes reasonable, sometimes not really so.)

One of the principles of the Pythonic philosophy, I believe, is that "explicit is better than implicit," so Python generally avoids automatic type casting and error recovery, which are features of more "implicit- friendly"languages like Perl.

Although the try... except form can be a bit verbose, in my opinion it has a lot of advantages in terms of clearly showing where an exception may occur and what the control flow is around that exception.

like image 45
Dan Lenski Avatar answered Nov 03 '22 00:11

Dan Lenski