I have seen questions similar to this but not quite the same. I have an expression
if foo == ....
return -1
elif myFunction(bar) != -1:
return myFunction(bar)
elif ...
I don't want to calculate myFunction(bar)
twice. If it were simply an if
, I could do
temp = myFunction(bar)
if temp != -1
return temp
However doing this with an elif
would result in unnecessary calculations of temp
if we were to follow the intitial if
.
I can see a solution using an
if ...
else
temp = myFunction(bar)
if temp != -1:
return temp
elif ...
But that now starts to become more ugly. Is there a better way to accomplish this?
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False , it checks the condition of the next elif block and so on. If all the conditions are False , the body of else is executed.
Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression) while (controlling expression)
Use the elif condition is used to include multiple conditional expressions after the if condition or between the if and else conditions. The elif block is executed if the specified condition evaluates to True .
If you do this a lot, it might pay to have a memoizing decorator around. The only memoizer that is currently in the standard library (for newer Python 3.x) is lru_cache
, which is overkill, but shows the general idea:
>>> def func():
... print("foo")
... return 1
...
>>> if func():
... print(func())
...
foo
foo
1
Now memoize func
:
>>> from functools import lru_cache
>>> func = lru_cache(1)(func)
>>> if func():
... print(func())
...
foo
1
If you do not want to call myFunction(bar) twice then there is no other way than using an intermediate variable to store the result in. People here start proposing complex caching solutions for this. This can be pretty convenient in extreme cases, but before doing so, let's get back to the basics a bit. You should make proper use of the fact that you want to return from within your conditional blocks. In these situations you can save many else
s. What follows now basically is the code block from your question, but without dots, with proper indentation, and with names according to PEP8:
if foo == "bar"
return -1
elif myfunction(bar) != -1:
return myfunction(bar)
else
return None
It can easily be replaced with:
if foo == "bar"
return -1
t = myfunction(bar)
if t != -1:
return t
return None
As already stated in another answer, you can call your function twice if it does not affect the performance of your code. The result would look as simple as
if foo == "bar"
return -1
if myfunction(bar) != -1:
return myfunction(bar)
return None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With