[Cython] how to initialize my c array in a quick way?

Stefan Behnel stefan_ml at behnel.de
Fri Nov 14 17:43:33 CET 2008


Hi,

Robert Bradshaw wrote:
> On Nov 13, 2008, at 2:30 PM, Stefan Behnel wrote:
>> Greg Ewing wrote:
>>> You can do
>>>
>>>    a[0], a[1], a[2], a[3], a[4] = 1, 3, 28, 5, 3
>>>
>>> which will get turned into a series of assignments.
>>>
>>> Ideally, what you *should* be able to do is
>>>
>>>    a[:] = 1, 3, 28, 5, 3
>> In Cython, you can now do
>>
>> 	cdef int a[5]
>> 	a[:] = [1, 3, 28, 5, 3]
>>
>> or
>>
>> 	cdef int a[20]
>> 	a[1:6] = [1, 3, 28, 5, 3]
>>
>> or even
>>
>> 	cdef int a[20]
>> 	start = 1
>> 	end = 6
>> 	a[start:end] = [1, 3, 28, 5, 3]
> 
> Very cool.

You did most of the work already.


>> However, the way it's currently implemented does no bounds  
>> checking, so it's
>> pretty easy to shoot yourself in the foot when you assign non- 
>> existing slices.
>> It's actually not so easy to determine at compile time how long the  
>> lhs slice
>> is, and how long the assigned sequence is.
>>
>> There's definitely more room for improvements. :)
> 
> Ouch. We can make sure (at runtime) that the rhs has the right size,

That's what I thought, too. There's a couple of cases that we can handle
efficiently, and some where we can add runtime checks.

Stefan



More information about the Cython-dev mailing list