Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug? Variables are identical references to the same string in this example (Python)

This is for Python 2.6.

I could not figure out why a and b are identical:

>>> a = "some_string"
>>> b = "some_string"
>>> a is b
True

But if there is a space in the string, they are not:

>>> a = "some string"
>>> b = "some string"
>>> a is b
False

If this is normal behavior, could someone please explain what is going on.

Edit: Disclaimer ! This is not being used to check for equality. I actually wanted to explain to someone else that "is" is only to check identity, not equality. And from the documentation I had understood that references created in this way will be different, that a new string will be created each time. The very first example I gave threw me off when I couldn't prove my own point!

Edit: I understand that this is not a bug, and interning was a new concept for me. This seems to be a good explanation.

like image 264
sarshad Avatar asked Nov 12 '10 14:11

sarshad


People also ask

How do you know if two variables reference the same object?

The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.

How do you check if two objects are the same in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=

How do you print the representation of a variable?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

Is Python a command?

The “is keyword” is used to test whether two variables belong to the same object. The test will return True if the two objects are the same else it will return False even if the two objects are 100% equal. Note: The == operator is used to test if two objects are the same.


1 Answers

Python may or may not automatically intern strings, which determines whether future instances of the string will share a reference.

If it decides to intern a string, then both will refer to the same string instance. If it doesn't, it'll create two separate strings that happen to have the same contents.

In general, you don't need to worry about whether this is happening or not; you usually want to check equality, a == b, not whether they're the same object, a is b.

like image 60
Glenn Maynard Avatar answered Nov 11 '22 12:11

Glenn Maynard