Puzzled by "is"

Erik Max Francis max at alcyone.com
Thu Aug 9 17:24:42 EDT 2007


John K Masters wrote:

> OK fiddling around with this and reading the docs I tried:-
> a = 'qqqqqqqqqq' #10 q's
> b = 'qqqqqqqqqq' #10 q's
> a is b
> true
> c = 'q' * 10
> c
> 'qqqqqqqqqq' #10 q's
> d = 'q' * 10
> d
> 'qqqqqqqqqq' #10 q's
> c is d
> false
> 
> So from what I've read "==" tests for equivalence, "is" tests for identity but
> that does not explain the behaviour above.

Using the `is` test between non-sentinel immutable objects (e.g., 
integers, floats, strings) is _completely pointless_.  Since immutable 
objects cannot be changed, it is up to the interpreter (and thus can 
vary from version to version and implementation to implementation) 
whether or not to "cache" the objects and reuse them, or whether or not 
to create new ones.  You should never be testing such objects for 
identity (`is`); you should only be testing them for equality (`==`).

The only time it makes sense to use the `is` operator with immutable 
objects is when you're dealing with a sentinel object, e.g., `None`, or 
a custom sentinel object (e.g., `mySentinel = object()`), because that 
is the only time you actually _are_ interested in identity.  All other 
times you are not really interested in identity.

Sample code as above is essentially showing unimportant implementation 
details that should never concern you.  Don't use `is`, use `==`.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Chance favors the trained mind.
    -- Louis Pasteur



More information about the Python-list mailing list