Python 中的字节总是八位字节吗?

Are bytes always octets in Python?

是否存在断言失败的 Python 实现:

assert all(byte in range(256) for byte in any_bytes_object) # Python 3 semantics 
assert all(byte in range(256) for byte in map(ord, any_bytes_object)) # Python 2

POSIX specifies explicitly that CHAR_BIT == 8 (8 bits per byte)。 Python中有类似的保证吗?它在某处记录了吗?

Python 2 reference says: "Characters represent (at least) 8-bit bytes."

如果未定义 bytes 名称(在旧的 Python 版本上),例如,在 Jython 2.5 上,那么问题是关于 str 类型(字节字符串),即 bytes = str 在 Python 2.

字节对象 Python 3 documentation 表示

bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256

并且 bytearray 类型在 Python 3 and Python 2

中都有记录

a mutable sequence of integers in the range 0 <= x < 256

所以语言是在8位字节的假设下设计的。


Python 2 数据模型部分说 "at least" 8 位似乎只是 Python 2 文档没有很好地保持最新的地方之一与 Python 3 文档相比。它至少可以追溯到 Python 1.4,早在他们不确定是否要支持奇怪的字节大小的早期。

自从至少在 2.0 版本中引入了 unicode 支持以来,文档中到处都是将 bytestring 类型称为“8 位字符串”。 Python 不像 C 那样严格指定,但我想说 Python 2.0 或更高版本的任何 "conforming" 实现都必须有 8 位字节。

除了官方文档,我们还可以参考引入字节对象的Python增强建议。

PEP 358 -- The "bytes" Object指定:

A bytes object stores a mutable sequence of integers that are in the range 0 to 255.

我们知道 bytes 对象最终是 不可变的这个规范不能完全适用 和 'range' 部分其中可能也没有实际意义。

有趣的是,PEP 3137 -- Immutable Bytes and Mutable Buffer,它部分取代了 PEP 358(并将字节指定为 immutable 并将字节数组引入为 mutable equivalent) 仅指定您可以 放入 字节对象和 bytearrays ("int[eger]s in range(256)") 的内容,但不指定其中可能 出来的内容 .

PEP 根本没有提到 "bit" 或 "bits"。 (虽然我们从按位布尔运算中知道 Python 整数如何映射到位模式,所以我希望那里不会有任何意外。)

Python 3

Since Python 3.0,Python 语言参考指定:

A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256.

Python 2

Before that(即最多 Python 2.7),它指定(如问题中已经提到的):

The items of a string are characters. […] Characters represent (at least) 8-bit bytes.

(强调已添加。)

请注意 Python 2 没有 bytes 对象。为了在 Python 2 中保存字节分块二进制数据的不可变序列,通常使用字符串 were/are。 (相比之下,Python 3 个字符串仅用于文本数据,并且更等同于 Python 2 的 unicode 对象而不是 Python 2 个字符串。)

但是...

Python 2 ord() function 的文档提到“8 位字符串”并将它们与 unicode 对象进行对比。这可能暗示所有非 unicode Python-2 字符串都是 8 位字符串,但我不会指望这一点。

结论

提供 Python-3 兼容 bytes 对象的 Python 实现将被限制为仅在其中包含 8 位字节。符合 Python 2 的 Python 实现不会受此约束(作为 bytes 对象,如果它具有一个对象,将是未指定的)并且如果您使用它的 Python-2 兼容的字符串作为替代,也不会对最大字节大小(实际上是字符大小)有任何保证,除非实现声明了它自己的一些保证。