Improved struct module

Robin Boerdijk boerdijk at my-deja.com
Sun Oct 10 08:50:09 EDT 1999


Hi all,

I would like to make a case for replacing the current Python
struct module with an improved version of it. I think the
struct module contains very useful functionality, but the
interface functions (pack and unpack) are inconvenient
for a number of situations.

To fix the pack/unpack inconvenience, I have written an xstruct
module that extends the struct module with a new structdef
function to *define* packed binary data structures (similar to
C's struct keyword).

In short, this function works as follows:

1. You first create a structdef object that defines the layout
and the fields of a packed binary data structure.

>>> import xstruct
>>> Person = structdef(xstruct.big_endian, [
...   ("name", (xstruct.string, 12)),
...   ("age",  (xstruct.unsigned_short, 1))
... ])

2. Now you can create actual struct objects from this structdef
object and manipulate them as if they were regular Python class
objects.

>>> john = Person()
>>> john.name = "John Smith"
>>> john.age = 25
>>> john.age
25

3. To access the internal packed binary data buffer, you can
use the Python str() function or use the object's buffer
interface.

>>> str(s)
'John Smith\000\000\000\031'

>>> open("tmp", "w").write(john) # uses buffer interface
>>> open("tmp", "r").read()
'John Smith\000\000\000\031'

You can also (re-)create structure objects from binary buffers,
but that's explained in detail at:

http://www.sis.nl/python/xstruct/xstruct.html

>From this page, you can also download the source code and a
pre-built Windows DLL of the xstruct module so you can try
things out yourself. Please do and let me know  what you
think. If there is enough positive feedback, I would like
to see the xstruct module becoming part of the core Python
distribution, replacing the current struct module.

Cheers,

Robin
(mailto:boerdijk at my-deja.com)


Sent via Deja.com http://www.deja.com/
Before you buy.




More information about the Python-list mailing list