Implementing ?: in Python
Friday, November 24th, 2006Python (at least up to version 2.4) doesn’t have a much needed ?: operator. Here’s how you can hack it yourself (I’m not sure if I would use it, except for very special situations, though).
# if-then-else function taking functions as arguments.
def ite(condition, true, false):
if condition:
return true()
else:
return false()
# Call it like this.
ite(condition, lambda:arg_true, lambda:arg_false);
# Just to check if it really works
def fun(arg):
print "Evaluated "+str(arg)
return arg
print ite(0, lambda:fun(1), lambda:fun(0));
print ite(1, lambda:fun(1), lambda:fun(0));