[Tutor] Buffer's?

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 11 Jun 2001 22:13:04 -0700 (PDT)


On Mon, 11 Jun 2001, Allan Crooks wrote:

> Can anyone explain to me what the buffer function actually does? I
> can't find much mention about it in the Python documentation.....

Hmmm!  I've never encountered the buffer function before!  Let's take a
look...


###
>>> buffer
<built-in function buffer>
>>> print buffer.__doc__
buffer(object [, offset[, size]) -> object

Creates a new buffer object which references the given object.
The buffer will reference a slice of the target object from the
start of the object (or at the specified offset). The slice will
extend to the end of the target object (or with the specified size).
###


Don't worry if this doesn't make sense to you; it's gibberish to me too...
*grin* I wonder why such a function would be useful?  There's a reference
to a thread on the main Python list that talks about buffer() here:

    http://mail.python.org/pipermail/python-list/1999-October/013886.html

>From reading this, it sounds like buffer is meant to make it easy to pass
in huge slices of information back and forth between functions.  Wait,
wait!  I see now!


Buffers allow us to take "slices" of our lists.  Unlike normal slices
though, these buffers don't make a copy of the original list.  To see why
buffers are useful, let's show that regular Python slices are actually
copies of an original list:

###
>>> mylist = range(5)
>>> mylist
[0, 1, 2, 3, 4]
>>> myslice = mylist[-2:]
>>> myslice
[3, 4]
>>> myslice[0] = 'three'
>>> myslice
['three', 4]
>>> mylist
[0, 1, 2, 3, 4]
###

So that's how slices work, by copying the section we're interested in as a
whole new list.

Normally, this copying behavior is a good thing, because it lets us fiddle
around with small pieces of a list without having disturbed the main list.  
However, it's a nightmare if we need to work with huge slices, since
copying can be expensive.  Buffers, then, act like slices: the only
difference is that they shouldn't copy the original list.

It's a little hard for me to show practical examples using buffers,
because, frankly, I've haven't worked with them yet.  *grin* Also, the
documentation on them seems really sparse --- I suspect that it's not
quite popular yet, since Python lists apparently doesn't support the
buffer interface yet.  Still, you might want to ask on comp.lang.python
and see if anyone is using it.


There's another reference to Buffer object in the Python/C API here:

    http://python.org/doc/current/api/bufferObjects.html

which suggests that buffer() is a sort of function that one shouldn't
touch unless you're a real efficiency enthusiast.


Sorry about the incomplete information!