Result of ``a is b''

David M. Cooke cookedm+news at physics.mcmaster.ca
Tue Mar 16 18:00:04 EST 2004


At some point, axelboldt at yahoo.com (Axel Boldt) wrote:

> David MacQuigg <dmq at gain.com> wrote 
>
>> >>> x = 'akdijfkdienlskfi'
>> >>> y = 'akdijfkdienlskfi'
>> >>> x is y
>>  True
>> >>> x = 'a b'
>> >>> y = 'a b'
>> >>> x is y
>>  False

And you get different results in different contexts:
In [17]: def f():
   ....:     x = 'a b'
   ....:     y = 'a b'
   ....:     return x is y
   ....: 
In [18]: f()
Out[18]: True

> Wow. So it seems that the action of "is" on immutables is unspecified
> and implementation dependent, thus useless to the programmer.

No, it's entirely specified. 'is' is 'is the same object'. The
implementation-specific part is in the *creation* of the immutable
object: when you specify 'akdijfkdienlskfi' in your code twice, the
interned object is used the second time -- so you actually only have
one object. In my example above, the compiler knew 'a b' was
duplicated, so it only has one copy of 'a b' stored in the function object.

> Maybe one could redefine "is" on immutables as follows: for strings
> and numbers it acts as "==", for tuples it acts as componentwise "is".
> That would be a more useful operator IMHO.

Why? If what you need is equality, and not object identity, use '=='.

Personally, almost all my uses of 'is' are of the form 'x is None' or
'x is not None'.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list