Python uses the result of a function to decide whether to use the result of a function
Often you want to use it None
as a return value for functions. Is there a Python idiom to avoid calling a function twice if you want to either do one thing if the function returns None
and if you don't use the function's result. Below is a silly example.
def foo(a, b):
if b == 0:
return(None)
else:
return(a/b)
a = b = 2
if foo(a, b) is None: #Do one thing. 1st call to function.
print('b cannot be null')
else: #Use the result of function. 2nd function call.
print('The result is: ' + str(foo(a,b)) )
Is this stateful option an alternative (with only one function call, but need to assign the result, which can be huge, to a variable) ?:
res = foo(a, b)
if res is not None:
print('The result is: ' + str(res) )
else:
print('b cannot be null')
source to share
In your example, foo returns None
to mean: "Something is wrong in the parameters and I cannot return a valid value." In this case, it would be better to use an exception:
def foo(a, b):
if b == 0:
raise ValueError("b can't be zero")
else:
return a/b
So, if b is null, foo will return nothing - and you don't have to check the return value to see if it is valid or if it means "something happened." If foo returns something, you are sure it is a valid result.
Now, to use foo, you must use a try
... block except
:
a = 2
b = 0
try:
print('The result is: ' + str(foo(a,b)) )
except ValueError as msg:
print(msg)
# b can't be zero
If you don't put a call foo
in a block like this, your program will stop with a nice informative error message:
foo(a, b)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-36-89e9686ab4be> in <module>()
14 print(msg)
15
---> 16 foo(a, b)
<ipython-input-36-89e9686ab4be> in foo(a, b)
1 def foo(a, b):
2 if b == 0:
----> 3 raise ValueError("b can't be zero")
4 else:
5 return a/b
ValueError: b can't be zero
which is good too, because your program should crash immediately when something goes wrong.
source to share