I’m trying to write a python function in a functional way. The problem is I don’t know, how to transform an if conditional into a functional style. I have two variables: A and C, which I want to check for the following conditions:
def function():
if(A==0): return 0
elif(C!=0): return 0
elif(A > 4): return 0
else: someOtherFunction()
I looked at the lambda shortcircuiting, but I couldn’t get it to work.
I thank you in advance for your help!
From the link you posted:
So instead of
if-statements, you could use a conditional expression:or, (especially useful if there were many different values):
By the way, the linked article proposes
as a short-curcuiting equivalent to
The problem is they are not equivalent! The boolean expression fails to return the right value when
<cond1>is Truish butfunc1()is Falsish (e.g.Falseor0orNone). (Or similarly when<cond2>is Truish butfunc2is Falsish.)is written with the intention of evaluating to
func1()when<cond1>is Truish, but whenfunc1()is Falsish,(<cond1> and func1())evaluates toFalse, so the entire expression is passed over and Python goes on to evaluate(<cond2> and func2())instead of short-circuiting.So here is a bit of interesting history. In 2005,
Raymond Hettinger found a similar hard-to-find bug in
type(z)==types.ComplexType and z.real or zwhenz = (0+4j)becausez.realis Falsish. Motivated by a desire to save us from similar bugs, the idea of using a less error-prone syntax (conditional expressions) was born.