Python not interning strings when in interactive mode?

只谈情不闲聊 提交于 2020-11-29 04:21:26

问题


When in a Python interactive session:

In [1]: a = "my string"

In [2]: b = "my string"

In [3]: a == b
Out[3]: True

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

In [5]: import sys

In [6]: print(sys.version)
3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609]

On the other hand, when running the following program:

#!/usr/bin/env python

import sys


def test():
    a = "my string"
    b = "my string"
    print(a == b)
    print(a is b)


if __name__ == "__main__":
    test()
    print(sys.version)

The output is:

True
True
3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609]

Why a is b has different outcome in the above two cases?

I am aware of this answer (and of course the difference between the == and is operators! that is the point of the question!) but aren't a and b the same object also in the first case? (interpeter?) since they point to the same (immutable) string?


回答1:


This is caused by string interning. See this question for another example.

In your example, CPython interns the string constants in the module but doesn't in the REPL.




回答2:


So the console creates two different objects when creating two strings, but the interpreter, when running code in a single function will reuse the memory location of identical strings. Here is how to check if this is happening to you:

a = "my string"
b = "my string"

print id(a)
print id(b)

If these two ids are the same, then a is b will return True, if not then it will return False

Looks like you are using anaconda, so I checked this in the console and found different ids and then wrote a function in the editor and executed it and got the same ids.

Note: Now that we know that is determines if two variable labels point to the same object in memory, I should say that is should be used sparingly. It is usually used to compare singletons like None a is None, for example. So don't use it to compare objects, use ==, and when creating classes implement the __eq__ method so you can use the == operator.



来源:https://stackoverflow.com/questions/41839886/python-not-interning-strings-when-in-interactive-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!