[Tutor] if n == 0 vs if not n

wesley chun wescpy at gmail.com
Thu Oct 8 21:58:22 CEST 2009

> Thanks all for the informative discussion. To re-confirm it was mostly
> for boolean checks like "if b == True".

wow, as the OP, you must have been surprised to see how far we have
taken your (seemingly) simple question. we went from boolean checks to
interning! commenting on my previous reply, i was addressing only the
boolean results when shortening the comparisons. as i mentioned
earlier, every Python object has the concept of a boolean value. zeros
and empty containers have False values while all others are True.

however, what i did *not* mention is that these (abbreviated)
comparisons do not work should you care to distinguish between
multiple Python objects/values that have the same boolean value. in
other words, "if not b" will catch False, None, 0, etc. if your
application is using 3 values like None (for unset value), False
(bad/errror code), and True (correct behavior), then None and False
will both cause the if clause to be executed. in other words, if you
care about the actual objects, then you need to use either "==" or
"is", rather than just checking their boolean outcomes.

now on to the difference between "==" vs. "is" and interning. "==" is
the object *value* comparison operator while "is" is the object
*identity* comparison operator. although "is 0" does work, it's easier
to read and less confusing than "== 0". also as others have already
mentioned, it's not a good idea to rely on the undocumented underlying
implementation, and for it to stay consistent. for example, back in
the earlier 2.x releases, the interned integer range was (-1, 101).
when i worked on the 2nd edition of Core Python, i still had that
range in the original manuscript. i then discovered that it changed to
(-5, 256)... no one warned me ahead of time, and i was not paying
enough attention to the python-dev list!

again, the bottom line is to *not* rely on the implementation because
it is always subject to change, granted not for numbers like -1, 0, 1,
but why confuse your fellow Python coder? "is" is better suited for
constants that are not numbers and that is always only one instance
of: None, True, False.

best regards,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Python Web Development with Django", Addison Wesley, (c) 2009

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca

More information about the Tutor mailing list