Use of the "is" statement

Gary Herron gherron at islandtraining.com
Fri Jun 27 11:38:50 EDT 2008


Joel Corbin wrote:
> Hello,
>
> I'm trying to clarify what exactly the behaviour of the is statement 
> is (or should be). Naturally, this has been nearly impossible to 
> google for, even using quotations... It is my impression that the is 
> statement should be equivalent to "==", at least on some level. 
> However, this equivalency seems to be inconsistent for reasons I can't 
> decipher. Out of the following 3 cases, only 2 return True. What is 
> the difference (and why is there one) in the third case?

Comparing two numbers or strings with "is" is equivalent to asking if 
the two numbers or strings are stored in the same location in memory.  
But since you have no control where values are stored when you bind them 
to a name, this is completely pointless.

In
  a=15
  b=15
it is implementation dependent whether the value 15 is stored once and 
refereed to twice, or stored twice. 

In short:  *never* use "is".

(A longer answer can find some uses cases for "is", but stick with the 
short answer for now.)

Gary Herron

>
> Python 2.5.2
> >>> 'string' is 'string'                   #simple assignment works
> True
> >>> s = 'string'      
> >>> s is 'string'        
> True
> >>> def make_string():   return 'test'     #but function behaviour varies
> >>> def arg_to_str(arg): return str(arg)
> >>> make_string() is 'test'
> True
> >>> arg_to_string('works') is 'works'      # this works
> True
> >>> arg_to_string(15) is '15'              # but this doesnt
> >>> arg_to_string(15) is arg_to_string(15) # nor this!
> >>> arg_to_string(15)
> '15'
> >>> arg_to_string(15) == arg_to_string(15)
> True
>
> This became a problem when I was using file.tell() and again when 
> using a custom function. If I am using is in the wrong context, what 
> is the right one?
> Joel
>
> ------------------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list