Yet another way to code the conditional operator to simulate the C's "a?b:c" ternary operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
def If(cond, truepart, falsepart): import inspect # Get the global namespace. globalns = globals() # Get the caller namespace localns = inspect.currentframe(1).f_locals # Evaluate according to 'cond' if cond: return eval(truepart, globalns, localns) else: return eval(falsepart, globalns, localns) # Example of use def spam(x): print If(x==0, '"Is zero"', '1.0/x') spam(4) # prints 0.25 spam(0) # prints "Is zero"
Alex Martelli's recipe "conditional in expressions" provides many ways to code the conditional operator. This is just another way that I feel resembles the C operator very closely.
By enclosing with '', the expressions on the true and false parts are not evaluated, so the "short-circuit" behavior is simulated (the price is making the code a bit uglier).
Also, the use of the inspect module allows to set the namespaces correctly, in order to evaluate variables which appear inside the strings.
It could be modified to allow statements in the true and false parts (changing the eval by an exec, essentially).