Wednesday, March 17, 2010

Python Conditional Expressions

New in Python 2.5 was the conditional expression. The expression can be used for short, conditional variable assignments where a full-blown if statement looks like overkill. At first I thought the syntax felt awkward compared to conditional expressions in other languages. But I think I can see the reasoning behind it now. It uses words which always read clearer than symbols do.

So is there any real benefit to using conditional expressions over if statements? Not really. It might serve as beneficial when setting instance attributes and you want to make sure there is a default value. This would be a rather large if statement if you are initializing several attributes. As long is the intent is clear, I say go for it if it cuts down the number of lines while maintaining readability.

And, there is no performance gain by using this construct. It is the same thing as an if statement, just arranged differently. Here is an example. The following two functions are essentially identical in execution time.
from timeit import Timer

def expression():
result = True if False else False

def statement():
if False:
result = True
else:
result = False

if __name__ == "__main__":
expression_timer = Timer("expression()",\
"from __main__ import expression")
statement_timer = Timer("statement()",\
"from __main__ import statement")

print "EXPRESSION:", expression_timer.timeit()
print "STATEMENT:", statement_timer.timeit()

No comments :

Post a Comment