3 ms·
Python is a little better than Perl or PHP on this; it won't treat the string "0" as false. It does, however, treat both 0 and None as false, and also 0.0 == 0
by kragen 15y ago
Python is a little better than Perl or PHP on this; it won't treat the string "0" as false. It does, however, treat both 0 and None as false, and also 0.0 == 0 == False, which is the same kind of potential bug.
Generally I find that Python's avoidance of implicit string type conversions means that I almost never have this kind of bug in my Python.
On another note, `myvar is 0` is undefined behavior; Python implementations can perfectly legitimately return False for that even if myvar is, in fact, the integer 0. Try this, in Python 2.7.3:
>>> x = 257
>>> x is 257
False
>>> x = 257; x is 257
True
>>> 257 is 2**8 + 1
False
>>> 256 is 2**8
True
>>> x = 256
>>> x is 256
True
That's because `is` denotes object identity, not value equality, and for immutable objects like integers, strings, and tuples of immutable objects, object identity is fair game for optimization. In the above, "is" gives us a fascinating window into the particular optimization decisions taken by the CPython 2.7.3 interpreter. But, child, if you want your code's behavior to depend on some problem domain instead of interpreter optimizations, don't use "is" to compare integers!
- toyg 15y agoYes child, check this out: http://lateral.netmanagers.com.ar/weblog/posts/BB979.html http://lateral.netmanagers.com.ar/weblog/posts/BB979.html , in particular my comment from two months ago. http://lateral.netmanagers.com.ar/weblog/posts/BB979.html#comment-424219673 http://lateral.netmanagers.com.ar/weblog/posts/BB979.html#co... and see where I'm coming from.