这是CPython实现如何选择缓存字符串文本的一个怪癖。具有相同内容的字符串文本可以引用同一个字符串对象,但它们不必引用。'string'恰好在'string '不存在时被自动截取,因为'string'只包含Python标识符中允许的字符。我不知道为什么他们会选择这个标准,但事实确实如此。在不同的Python版本或实现中,行为可能不同。在
来自cpython2.7源代码,^{},第28行:Interning strings (ob_sstate) tries to ensure that only one string
object with a given value exists, so equality tests can be one pointer
comparison. This is generally restricted to strings that "look like"
Python identifiers, although the intern() builtin can be used to force
interning of any string.
您可以在^{}中看到执行此操作的代码:/* Intern selected string constants */
for (i = PyTuple_Size(consts); i >= 0; ) {
PyObject *v = PyTuple_GetItem(consts, i);
if (!PyString_Check(v))
continue;
if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
continue;
PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
}
另外,请注意,interning与Python字节码编译器合并字符串文本是一个独立的过程。如果让编译器一起编译a和b赋值,例如将它们放在一个模块或一个if True:中,您会发现a和{}将是同一个字符串。在