False == 0 in Python!?

July 19, 2008 – 8:01 pm

bug.pngI came across a very strange error when tweaking the skime compiler. I decided to use the more specific push_0 and push_1 instruction instead of the general push_literal when the literal is 0 and 1 respectively. However, after added this code, several test cases was broken immediately.

After examining the execution of the failing test cases, I found that I got a 0 when expecting a False. And I finally found the problem is that I use if literal == 0 to test whether I got a literal 0. But unfortunately, False == 0 (as well as True == 1) evaluates to True in Python. So there’s the bug.

I’m feeling rather surprised when I found False == 0. Yes, I know we use 0 to represent a false value in C, but I really don’t expect it to be in Python — such a high-level and duck-typing language. However, since it is already there, I have to remember.

  1. 2 Responses to “False == 0 in Python!?”

  2. If you want to check that something is “exactly” false (or exactly True, or exactly None), use the “x is False” rather then the “x == False”.

    Any non-zero value is “true” while any zero value is “false”.

    By Mithro on Jul 21, 2008

  3. @Mithro,
    Yes, you are right. But here I’m in fact willing to check something that is exactly 0, but I guess I can’t use x is 0 here. I don’t know how Python implement integers. If it is encoded as a immediate value in the pointer, every 0 should be the same. However, I found id(0) will be different when I start a different Python session.

    By pluskid on Jul 21, 2008

Post a Comment