Use of the "is" statement

Jason Scheirer jason.scheirer at gmail.com
Fri Jun 27 12:01:17 EDT 2008


On Jun 27, 8:38 am, Gary Herron <gher... at islandtraining.com> wrote:
> 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

Is is identity, not equality. It's the equivalent of comparing two
pointers' addresses in C.

You can get the memory location of an object x in python using the
id() function, so remember the following:

a is b

IS THE SAME THING AS

id(a) == id(b)

The reason 'is' works for things like 'a is None' is because there is
only one None builtin in memory ever, all the variables assigned to
none merely point at it.



More information about the Python-list mailing list