1

I want to check if two variables refer to different objects. I know that in python Strings are objects too (I'm a Java programmer learning python now). I read that is checks for references while ==checks for values, but when I ran the following code it seemed it checked for values!

name1 = "ABC D"
name2 = "ABC D"

if name1 is name2:
    print "Equal!!!"
else:
    print "NOT equal!!!"

It gives equal!

Jack Twain
  • 6,273
  • 15
  • 67
  • 107

2 Answers2

4

The python interpreter will intern small string literals (where "small" is implementation-dependent). This is why name1 is name2 gives True: the two names refer to the same string object.

CPython, and probably other implementations as well, does not intern the result of runtime expressions, so if you really, really need your strings to be different objects, you can build them dynamically. For example:

In [1]: prefix = 'ABC '

In [2]: a = prefix + 'D'

In [3]: b = prefix + 'D'

In [4]: a is b
Out[4]: False

On the other hand, if you're just experimenting to see what will happen, but the strings you care for already come from runtime expressions, you should not need to do anything special.

I would remark, anyway, that string interning is an implementation detail. Depending on your use case, if you do need to ensure that your objects always have different identities, you should probably use a custom class. For example:

class Marker(str):
    __slots__ = ()

This will probably work as expected:

In [6]: Marker('ABC D')
Out[6]: 'ABC D'

In [7]: Marker('ABC D') is Marker('ABC D')
Out[7]: False

In [8]: Marker('ABC D') == Marker('ABC D')
Out[8]: True

unless you plan to use your objects as keys in a dictionary and you expect distinct objects to be distinct keys. But, in that case, plain strings would also not work.

tawmas
  • 7,443
  • 3
  • 25
  • 24
2

As in the comment from Matthias, name1 = "ABC D" is just assigning the reference of the object "ABC D" to name1.

If in doubt, you can actually inspect the underlying object by id() to check if python works the same way as you think :)

name1 = "ABC D"
name2 = "ABC D"
name3 = "Different string"
print id(name1)
print id(name2)
print id(name3)
cybeliak
  • 76
  • 3