为什么不能在Python中转换字节?

huangapple go评论61阅读模式
英文:

Why can't you intern bytes in Python?

问题

根据Python文档中提到的,sys.intern() 只接受字符串对象。我理解为什么sys.intern不支持可变类型。但至少还有一种不可变类型可以使用内部化:bytes

所以我的问题是:Python为什么不支持bytes的内部化?

英文:

As mentioned in Python documentation, sys.intern() only accepts string objects. I understand why mutable types are not supported by sys.intern. But there's at least one more immutable type for which interning would make sense: bytes.

So here's my question: is there any particular reason why Python interning doesn't support bytes?

答案1

得分: 4

这是在十年前的Python-Dev邮件列表上建议的1。答案是:

> 主要区别在于sys.intern()会在所有外部引用消失时删除已经intern的字符串。这需要弱引用的能力(str和bytes都没有),或者需要对象析构函数的特殊合作(这就是为什么sys.intern()只能用于str而不能用于任意对象的原因)。

显然,可以添加对bytes的支持,但这似乎是非常小众的需求,不太可能成为标准Python的一部分。这并不妨碍您创建自己的等效实现,除非您需要它的唯一原因是为了提高字典键查找的速度。我从未见过有人将bytes用作字典键,但我相信有些人可能会这样做。

英文:

This was suggested a decade ago on the Python-Dev mailing list. The answer is:

> The main difference is that sys.intern() will remove the interned
strings when every external reference vanishes. 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).

Clearly it is possible to add support for bytes, but it seems very niche, not something standard Python is likely to add. 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.

huangapple
  • 本文由 发表于 2023年1月9日 00:38:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定