3 ms·
It's not Perl. I recently had a conversation with a friend who didn't like me using "if myvar == 0:" or "if myvar is 0:" in python code rather than "if myvar:".
by toyg 15y ago
It's not Perl. I recently had a conversation with a friend who didn't like me using "if myvar == 0:" or "if myvar is 0:" in python code rather than "if myvar:". Call me paranoid, but i like to be as explicit as possible in my checks, you never know when magic conversion tricks (which are often platform- or implementation-dependant) will end up biting you in the ass.
- maxerickson 15y agoUsing "if myvar is 0" exposes you to more implementation dependent behavior than "if myvar".
- toyg 15y agoI agree, but it's still more explicit in terms of what process is used to evaluate the content of myvar and what it should match, especially in a context where you're expecting a numeric value rather than a boolean.
- kragen 15y agoPython 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.