简体   繁体   中英

Why can't you intern bytes in Python?

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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