关于 CPython 中字符串 interning 的问题

2019-05-24 11:44:34 +08:00
 RitchieLee

小弟今天对 interning 还有 Python 中 str 类型的实现比较感兴趣

现在有一个问题,就是我看到了 PyUnicodeObject 这个相关的文件有一个函数 PyUnicode_InternInPlace,我看了下这个函数主要应该是做 interning 的,但是是否我们平常赋值 str 类型时就会调用这个函数呢?

还有一个点我也不太确定,就是 str 类型是不是在现阶段 (python3.3 之后) 底层实现就是 PyUnicdoeObject 了呢,这个我也暂时没有找到依据。看到了一个 pep 文件

PyUnicodeObject 主要内容在 Include/unicodeobject.hObjects/unicodeobject.c 两个文件

然后 PyUnicode_InternInPlace 定义在这里

1400 次点击
所在节点    Python
3 条回复
lrxiao
2019-05-24 12:08:22 +08:00
http://guilload.com/python-string-interning/ 应该只有 compile-time 的字符串才会 intern
https://docs.python.org/3.0/whatsnew/3.0.html py3 默认 Unicode string 作为 str
RitchieLee
2019-05-24 12:50:30 +08:00
@lrxiao 感谢,第二个链接我详细看看
如果过是交互器解释器的话,写在一行应该也会 interning,我之前看了这篇文章: https://www.codementor.io/satwikkansal/do-you-really-think-you-know-strings-in-python-fnxh8mtha
比如:
a,b="wtf!","wtf!"
a is b # True
lrxiao
2019-05-24 14:13:58 +08:00
@RitchieLee REPL 和普通 Py 程序应该都是要过同样的 compile 阶段的吧

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/567240

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX