简体   繁体   English

为什么不能在 Python 中实习字节?

[英]Why can't you intern bytes in Python?

As mentioned in Python documentation, sys.intern() only accepts string objects.如 Python 文档中所述, sys.intern()仅接受字符串对象。 I understand why mutable types are not supported by sys.intern .我明白为什么sys.intern不支持可变类型。 But there's at least one more immutable type for which interning would make sense: bytes .但是至少还有一种更不可变的类型对于实习来说是有意义的: bytes

So here's my question: is there any particular reason why Python interning doesn't support bytes ?所以这是我的问题:Python 实习不支持bytes有什么特别的原因吗?

This was suggested a decade ago on the Python-Dev mailing list .这是十年前在 Python-Dev 邮件列表上提出的建议。 The answer is:答案是:

The main difference is that sys.intern() will remove the interned strings when every external reference vanishes.主要区别在于 sys.intern() 将在每个外部引用消失时删除 interned 字符串。 It requires either weakref'ability (which both str and bytes lack) or special cooperation from the object destructor (which is why sys.intern() is restricted to str instead of working with arbitrary objects).它需要 weakref'ability(str 和 bytes 都缺乏)或 object 析构函数的特殊合作(这就是为什么 sys.intern() 仅限于 str 而不是处理任意对象)。

Clearly it is possible to add support for bytes , but it seems very niche, not something standard Python is likely to add.显然可以添加对bytes的支持,但它似乎非常小众,而不是标准 Python 可能添加的东西。 That doesn't stop you from making your own equivalent, unless the whole reason you want it is for dictionary key lookup speed.这不会阻止您制作自己的等价物,除非您想要它的全部原因是字典键查找速度。 I've never seen anyone use bytes as dictionary keys, but I'm sure some people do.我从未见过有人使用bytes作为字典键,但我相信有些人会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM