Fast construction of Python list from large C array of int's - Extension Module

Bernhard Herzog bh at intevation.de
Tue Nov 19 07:17:42 EST 2002


Alex Martelli <aleax at aleax.it> writes:

> quadric at primenet.com wrote:
> > PyObject * CreateListFromArray( int * array , int array_length)
> > {
> > PyObject * list = PyList_New( array_length);
> > 
> > for int i = 0 ; i < array_length ; i++ )
> >   {
> > PyList_SetItem( list , i , Py_LongFromLong( (long) array[i] )  );
> > }
> > 
> >   return list;
> > }
[...]
> > Any inherent dangers here?
> 
> Yes: not only pointer 'list', as you realize later, but also EACH pointer 
> resulting from PyLong_FromLong COULD be null, with dangerous
> results if you don't check.  Do check, and if you get any null, decref
> the ones you had previously added

Simply DECREFing the list should be enough if I recall the
implementation of the list correctly because if you create a list with
non-zero length all pointers stored in it are NULL so the destructor
knows which are actually filled with real python objects.

> and then raise out-of-memory.

The exception will already have been set by PyLong_FromLong, I think, so
CreateListFromArray should just return NULL.

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                           http://www.mapit.de/



More information about the Python-list mailing list