does python could support sequence of short or int?

Magnus Lycka lycka at carmen.se
Thu Mar 30 17:21:28 CEST 2006


momobear wrote:
> but what about buffer is not be declared in python program, it comes
> from a C function. and what about I want to treat a string as a short
> list?

Python is a high level language with much stronger typing than C.
If you want a list of integers, use a list of integers. Strings
are for text. You might well extract numeric values from a string that
you get from another source, and you can use array or struct for that,
but don't use that while processing numeric values in Python.

Sorry, but when I hear you, I see the image of someone who shoves dirt
into the trunk of a car, goes over to the front, tries to lift it with
his bare hands, and complains that this is a really clunky wheel-barrow.
;^)

Don't try to make Python into some kind of crippled C. It's much more
powerful than C if you use it as intended. Used backward, it will only
irritate you. I can well understand that you try to use C idioms if that
is what you know, but you should understand that this will often lead
you to bad Python solutions.

I don't quite understand how you intend that the interface between C
and Python would look. You can't just pass a raw C pointer to Python.
If you want that data to be managed by your C code, you need to provide
an API that you can access from Python that will make sense for Python.

If you e.g. pass a string as a return value from a wrapped C function,
you can e.g. use array or struct in Python to access it in a way that
makes sense in Python.

Assuming that your C function returns a string with 2 byte integers like
this:
 >>> s
'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00\x07\x00\x08\x00\t\x00'

You can easily make a list like this:

 >>> import struct
 >>> l = list(struct.unpack('h'*(len(s)/2), s))
 >>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]

If you don't need to manipulate it, you can skip the 'list()'
part and get an immutable tuple instead.

The advantage with struct over array in s case like this (as far as I
understand) is that you have control over endianness.



More information about the Python-list mailing list