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