什么是Python缓冲区类型?

What is Python buffer type for?

python中有一个buffer类型,但我不知道如何使用它。

在Python文档中,描述是:

buffer(object[, offset[, size]])

The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). A new buffer object will be created which references the object argument. The buffer object will be a slice from the beginning of object (or from the specified offset). The slice will extend to the end of object (or will have a length given by the size argument).


示例用法:

1
2
3
4
5
6
>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

在这种情况下,缓冲区是一个子字符串,从位置6开始,长度为5,并且它不占用额外的存储空间 - 它引用字符串的一个片段。

这对于像这样的短字符串不是很有用,但在使用大量数据时可能是必要的。此示例使用可变bytearray

1
2
3
4
5
>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

如果您希望在数据上有多个视图并且不希望(或不能)在内存中保存多个副本,这将非常有用。

请注意,buffer已被Python 3中名称较好的memoryview取代,但您可以在Python 2.7中使用。

另请注意,您无法在不深入C API的情况下为自己的对象实现缓冲区接口,即您无法在纯Python中执行此操作。


我认为缓冲是例如在将python连接到本机库时很有用。 (Guido van Rossum在此邮件列表中解释了buffer)。

例如,numpy似乎使用缓冲区来进行有效的数据存储:

1
2
import numpy
a = numpy.ndarray(1000000)

a.data是:

1
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>