Difference between 'is' and '=='

alex23 wuwei23 at gmail.com
Tue Mar 28 02:02:09 EST 2006


Felipe Almeida Lessa wrote:
> I said [constants defined in your code] can (maybe "should"?) be used with "is", and
> AFAICT I'm right as well:
> >>> b = a
> >>> b is a
> True

You should _never_ use 'is' to check for equivalence of value. Yes, due
to the implementation of CPython the behaviour you quote above does
occur, but it doesn't mean quite what you seem to think it does.

Try this:

>>> UPPERLIMIT = 100
>>> i = 0
>>> while not (i is UPPERLIMIT):
>>>     i+=1
>>>     print i

Comparing a changing variable to a pre-defined constant seems a lot
more general a use case than sequential binding & comparison...and as
this should show, 'is' does _not_ catch these cases.

- alex23




More information about the Python-list mailing list