"Diez B. Roggisch said:
So - your conclusion is basically right: use is on (complex) objects, not on
numbers and strings and other built-ins. The exception from the rule is
None - that should only exist once, so
foo is not None
is considered better style than foo == None.
But even better style is just `foo' or `not foo'. Or not,
depending on what you're thinking.
The key point between `is' and `==' has already been made -
- use `is' to compare identity
- use `==' to compare value
It's that simple, and it's hard to add to this without
potentially layering some confusion on it. While Python's
implementation makes the use of identity with small numbers
a slightly more complicated issue, there isn't a lot of
practical difference. To take a common case that has already
been mentioned here, if I define some constant symbolic values
as small integers, as long as I take care that their values
are distinct, I can reasonably use identity and ignore this
technical weakness. I can assume that no one is going to
supply randomly selected integers in this context. Meanwhile,
the use of identity clarifies the intent.
Depending, of course, on what the intent may be, which brings
us to None, and a point about values in Python that was brought
to a fairly brilliant light some years back by someone we don't
hear from often here any more, unfortunately.
- use `is' to compare identity
- use `==' to compare value
- use neither to test for `somethingness'
I'm not going to try to elucidate the theory of something and
nothing in Python, but suffice it to say that there are places
where it may be better to write
if not expr:
than
if expr is None:
or worse yet,
if expr == False:
That's what I think, anyway.
Donn Cave, (e-mail address removed)