Difference between 'is' and '=='

Peter Hansen peter at engcorp.com
Tue Mar 28 09:00:38 EST 2006


Joel Hedlund wrote:
>>This does *not* also mean constants and such:
> 
> <snip>
> 
>>    >>> a = 123456789
>>    >>> a == 123456789
>>    True
>>    >>> a is 123456789
>>    False
> 
> I didn't mean that kind of constant. I meant named constants with defined 
> meaning, as in the example that I cooked up in my post. More examples: os.R_OK, 
> or more complex ones like mymodule.DEFAULT_CONNECTION_CLASS.

If it weren't for the current CPython optimization (caching small 
integers) this code which it appears you would support writing, would fail:

   if (flags & os.R_OK) is os.R_OK:
       # do something

while this, on the other hand, is not buggy, because it correctly uses 
equality comparison when identity comparison is not called for:

   if (flags & os.R_OK) == os.R_OK:
       # do something

(I think you should give it up... you're trying to push a rope.)

-Peter




More information about the Python-list mailing list