为什么容器的最大尺寸有符号位?
Why does the maximium size of containers have a sign bit?
我查看了 Python 3.6 中 sys.maxsize
的帮助:
>>> help(sys)
[...]
maxsize -- the largest supported length of containers.
正在测试:
In [10]: '{:,}'.format(sys.maxsize)
Out[10]: '9,223,372,036,854,775,807'
In [11]: math.log2(sys.maxsize)
Out[11]: 63.0
它是 63 位,表示前导符号位。但是,容器的长度不能为负数。
这是怎么回事?
容器的最大大小在 Python 2.5 中从 231-1 增加到 263-1 . PEP 353: Using ssize_t as the index type, which introduced the change, says:
Why not size_t
An initial attempt to implement this feature tried to use size_t. It
quickly turned out that this cannot work: Python uses negative indices
in many places (to indicate counting from the end). Even in places
where size_t would be usable, too many reformulations of code where
necessary, e.g. in loops like:
for(index = length-1; index >= 0; index--)
This loop will never terminate if index is changed from int to size_t.
因此,限制源于使用 Python 特定 "indexing" 类型的决定,将其定义为有符号 (ssize_t) 而不是无符号 (size_t) 以简化负索引的处理。
我查看了 Python 3.6 中 sys.maxsize
的帮助:
>>> help(sys)
[...]
maxsize -- the largest supported length of containers.
正在测试:
In [10]: '{:,}'.format(sys.maxsize)
Out[10]: '9,223,372,036,854,775,807'
In [11]: math.log2(sys.maxsize)
Out[11]: 63.0
它是 63 位,表示前导符号位。但是,容器的长度不能为负数。
这是怎么回事?
容器的最大大小在 Python 2.5 中从 231-1 增加到 263-1 . PEP 353: Using ssize_t as the index type, which introduced the change, says:
Why not size_t
An initial attempt to implement this feature tried to use size_t. It quickly turned out that this cannot work: Python uses negative indices in many places (to indicate counting from the end). Even in places where size_t would be usable, too many reformulations of code where necessary, e.g. in loops like:
for(index = length-1; index >= 0; index--)
This loop will never terminate if index is changed from int to size_t.
因此,限制源于使用 Python 特定 "indexing" 类型的决定,将其定义为有符号 (ssize_t) 而不是无符号 (size_t) 以简化负索引的处理。