views:

60

answers:

3

I was checking a friend's code, and this pattern showed up quite a bit whenever he wrote functions that returned a boolean value:

def multiple_of_three(n):
    if (n % 3) is 0:
       return True
    else:
       return False

I maintain that it's simpler (and perhaps a bit faster) to write:

def multiple_of_three(n):
    return (n % 3) is 0

Am I correct that the second implementation is faster? Also, is it any less readable or somehow frowned upon?

+3  A: 

I very much doubt there is a compiler or interpreter still out there where there is a significant speed difference - most will generate exactly the same code in both situations. But your "direct return" method is, in my opinion, clearer and more maintainable.

Paul Tomblin
I wondered about performance because this pattern repeats in his code... like 15 times. So if there was a small difference it might become a significant backlog
Rafe Kettler
+3  A: 

I can't speak of the Python interpreter's exact behavior, but doing one way over another like that (in any language) simply for reasons of "faster" is misguided, and qualifies as "premature optimization". As Paul Tomblin stated in another answer, the difference in speed, if any, is quite negligible. Common practice does dictate, however, that the second form in this case is more readable. If an expression is implicitly boolean, then the if statement wrapper is frivolous.

See also http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize

tianon
A: 

The second form is the preferred form. In my experience the first form is usually the sign of an inexperienced programmer (and this does not apply solely to Python - this crops up in most languages).

Groky