Friday, June 23, 2006

The ternary operator in Python shows how to use selection from a tuple to substitute for the ternary operator.

A problem with this technique is that all the members of the tuple are evaluated prior to the truth condition test. So if you want to use an argument if it's present but a default if there's no argument, you cannot write

print "The argument is %s" : (sys.argv[1],"missing")[len(sys.argv)=1]

because the runtime will complain about the out of bounds on argv before it gets to the length test.

Instead you write

print "The argument is %s" : len(sys.argv)>1 and sys.argv[1] or "missing"

Which I suppose is not all that far from

print "The argument is %s" : len(sys.argv)>1 ? sys.argv[1] : "missing"