Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional python programming and conditionals

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!

like image 625
TheAptKid Avatar asked Dec 07 '22 11:12

TheAptKid


1 Answers

From the link you posted:

FP either discourages or outright disallows statements, and instead works with the evaluation of expressions

So instead of if-statements, you could use a conditional expression:

def function():
    return (0 if ((A == 0) or (C != 0) or (A > 4)) else
            someOtherFunction())

or, (especially useful if there were many different values):

def function():
    return (0 if A == 0 else
            0 if C != 0 else
            0 if A > 4 else
            someOtherFunction())

By the way, the linked article proposes

(<cond1> and func1()) or (<cond2> and func2()) or (func3())

as a short-curcuiting equivalent to

if <cond1>:   func1()
elif <cond2>: func2()
else:         func3()

The problem is they are not equivalent! The boolean expression fails to return the right value when <cond1> is Truish but func1() is Falsish (e.g. False or 0 or None). (Or similarly when <cond2> is Truish but func2 is Falsish.)

(<cond1> and func1())

is written with the intention of evaluating to func1() when <cond1> is Truish, but when func1() is Falsish, (<cond1> and func1()) evaluates to False, 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 z when z = (0+4j) because z.real is Falsish. Motivated by a desire to save us from similar bugs, the idea of using a less error-prone syntax (conditional expressions) was born.

like image 134
unutbu Avatar answered Dec 23 '22 07:12

unutbu