Use of the "is" statement

Joel Corbin zaikenv at gmail.com
Fri Jun 27 10:51:07 EDT 2008


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?

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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080627/f9580d4f/attachment.html>


More information about the Python-list mailing list