[Pyrex] Handling bytes

Stefan Behnel stefan_ml at behnel.de
Thu May 8 09:05:05 CEST 2008


Hi,

Brad Schick wrote:
> On 5/7/2008 10:49 PM, Stefan Behnel wrote:
>> Brad Schick wrote:
>>  
>>> Maybe I'd be better off using python strings
>>> with  PyString_FromStringAndSize and friends?
>>
>> Yes.
> 
> I guess strings a byte arrays is part of pre 3.0 python.

Well, Py3 has "bytes" and "bytearray". If you want to target Py3 only, go for
that.

BTW, work has started in Cython to generate code for Py3. It's still a long
way, but at least we're getting closer. :)


> It just seems
> so ugly in what is otherwise a fairly clean language. Particularly when
> the data sometimes starts life as a list. How do you go about stuffing
> 'bytes' into a string? With arrays as below? Or with cStringIO? Yuck and
> yuck ;)
> 
> data = [0,1,2,3,4,5,6,7]
> arr = array.array('B', data)
> str = arr.tostring()

Sure, why not? You can also create an empty string and fill it yourself:

   cdef int i
   cdef char* s
   py_s = PyString_FromStringAndSize(NULL, len(data))
   s = py_s
   for i in range(len(data)):
       s[i] = l[i]

(untested)

Stefan



More information about the Pyrex mailing list