Result of ``a is b''

Peter Hansen peter at
Tue Mar 16 22:07:31 CET 2004

Axel Boldt wrote:

> David MacQuigg <dmq at> wrote 
>>>>>x = 'akdijfkdienlskfi'
>>>>>y = 'akdijfkdienlskfi'
>>>>>x is y
>> True
>>>>>x = 'a b'
>>>>>y = 'a b'
>>>>>x is y
>> False
> Wow. So it seems that the action of "is" on immutables is unspecified
> and implementation dependent, thus useless to the programmer.

Absolutely not!  "is" does what it does, and the definition of what it 
does is very explicit.  It checks *identity*, not equality.  In both 
examples above, the code is semantically meaningless because you are 
checking identity on two things which you just created at the command 
line, out of thin air.  They may or may not be identical, but whether 
they are or not has no importance.

I'm not being very clear, but what I mean is that "is" should be used 
when *identity* is important to you.  For example, you have a particular 
object and you want to check whether a method call returns that 
particular object, perhaps as a "sentinel" value.  "is" is what you want 
here, because you are checking whether *that specific object* is being 
returned, not whether the returned item equals that object in value.

There are very good (and correct) times to use "is", but the trivial 
examples above aren't them...


More information about the Python-list mailing list