编程语言
首页 > 编程语言> > 带有空格的Python字符串,最后没有空格和不变性

带有空格的Python字符串,最后没有空格和不变性

作者:互联网

我了解到在一些不可变类中,__ new__可能会返回一个现有实例 – 这就是int,str和tuple类型有时对小值进行的操作.

但为什么以下两个片段的行为不同?

最后有一个空格:

>>> a = 'string '
>>> b = 'string '
>>> a is b
False

没有空间:

>>> c = 'string'
>>> d = 'string'
>>> c is d
True

为什么空间带来了差异?

解决方法:

这是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.

您可以在Objects/codeobject.c中看到执行此操作的代码:

/* 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将是相同的字符串.

标签:cpython,python,string,immutability,python-internals
来源: https://codeday.me/bug/20190917/1809452.html