这是CPython实现如何选择缓存字符串文字的一个怪癖.具有相同内容的字符串文字可以引用相同的字符串对象,但它们不必.当’string’不是因为’string’只包含Python标识符中允许的字符时,’string’碰巧会自动被中断.我不知道为什么这是他们选择的标准,但确实如此.在不同的Python版本或实现中,行为可能不同.
从CPython 2.7源代码,stringobject.h,第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));
}
另请注意,实习是与Python字节码编译器合并字符串文字的单独过程.如果让编译器一起编译a和b分配,例如通过将它们放在模块或if True:中,您会发现a和b将是相同的字符串.