is and == (is not other_thread)

Robin Thomas robin.thomas at starmedia.net
Thu Mar 1 07:41:00 CET 2001


At 10:33 PM 2/28/01 -0600, Grant Griffin wrote:
>Hi Gang,
>
>I've had a few of my own little questions about "is" and "==", vis-a-vis
>strings:

a is b # are a and b two references to a single object
a == b # are a and b references to "equivalent" objects or to a single object

if a is b, then a == b

>1) Are two strings that are equal in the "==" sense always guaranteed to
>be equal in the "is" sense?

No. There's a previous post explaining it well, I'll summarize:

String literals are "interned" by Python, so that it uses a single string 
object for every unique string literals it finds in the code. Strings built 
at run-time by concatenation or other means are not interned, and thus are 
always different objects.

 >>> s1 = "ab"
 >>> s2 = "ab"
 >>> s1 is s2
1
 >>> s1 == s2
1
 >>> s3 = "a" + "b"
 >>> s1 is s3
0
 >>> s1 == s3
1


>2) Is "is" faster than "==" for strings?

"is" is speedier than "==" for all object pairs save a pair of integers. 
Python does "is" and "==" with the same speed to a pair of integers.

>  Of hand, it would seem so.
>That's why I'm tempted to use it for string equality.  (OTOH, if strings
>can be "==" equal without being "is" equal, than I guess that's wildly
>false economy. <wink>)

Don't use the identity operator "is" to test object equality, just as you 
would not use the bitwise xor operator to test object equality. "is" and 
"==" are different operations meaning different things. Don't be tempted.

>3) Internally, does "==" for strings always begin with an "is"
>operation?

Comparison in CPython does an implicit "is" operation first for any objects 
except integers, which are speedily handled beforehand in a special case.


>(btw,-nobody-ever-answers-every-part-of-my-silly-multipart-questions,
>    -so-i-dare-you-folks-to-buck-the-trend-<wink>)-ly y'rs,

Use the source, Luke. All multipart questions are thus answered. This reply 
was your freebie.


--
Robin Thomas
Engineering
StarMedia Network, Inc.
robin.thomas at starmedia.net





More information about the Python-list mailing list