[Image-SIG] Proper application of the buffer interface

M.-A. Lemburg mal at lemburg.com
Fri Aug 6 15:15:14 CEST 1999

Mark Hammond wrote:
> M.-A. Lemburg <mal at lemburg.com> wrote in message
> <37AAA7FE.FFE0FD2 at lemburg.com>...
> > Fred L. Drake, Jr. wrote:
> > >
> > > David Ascher writes:
> > >  > Would it also make sense to make struct.pack()
> > >  > return a buffer object
> > >  > instead of a string?
> > >
> > >   Sounds like it to me.  If Guido agrees, I can make the changes.
> >
> > Wait... what's so bad about buffer(struct.pack()) ? Strings already
> > know the buffer interface, so this works just fine already.
> Well, struct.pack() does not return a string - it returns a chunk of
> memory.

The docs say:

pack (fmt, v1, v2, ...) 
     Return a string containing the values v1, v2, ... packed according to the given format. The
     arguments must match the values required by the format exactly. 

> So IMO it makes more sense to say "str(struct.pack())" if you really want a
> string.

While its arguable whether returning a string is the right
thing to do, simply returning a buffer object instead of
a string will certainly break code expecting a string -- you can't
rely on all C APIs using "s#" to parse the return value of
struct.pack(), even though most of them will probably.

Marc-Andre Lemburg
Y2000:                                                   147 days left
Business:                                      http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/

More information about the Python-list mailing list