Why Python's is and == are not the same thing, how one of them lies about numbers, and the single rule that keeps you safe.
I had a check that compared two numbers. Something close to this, simplified:
if parsed_id is expected_id : grant_access ()
Enter fullscreen mode
Exit fullscreen mode
It worked. Every test passed. Then one day, with slightly different data, the same comparison started returning False for two numbers that were obviously equal. Both were 257 . I printed them. They were identical. And parsed_id is expected_id was False .
So I changed the test data, and it went back to True . Smaller numbers worked. Bigger numbers did not. The comparison's correctness depended on how large the number was , which is not a sentence that should ever make sense.
The culprit was a single two-letter word I had used where I meant something else: is . In Python, is and == look interchangeable and are not.β¦