[Numpy-discussion] python user defined type

Christopher Barker Chris.Barker@noaa....
Thu Jul 10 18:30:13 CDT 2008

Nicolas Rougier wrote:
> Concerning the dtype argument during array creation, I thought it was
> here for somehow controlling the type of array elements. For example, if
> I use a "regular" numpy array (let's say a float array), I cannot set an
> item to a string value (it raises a ValueError: setting an array element
> with a sequence).

Yes, but numpy is designed primarily for numeric types: ints, floats, 
etc. It can also be used for custom types that are essentially like C 
structs (see recarray). The key is that a dtype desribes a data type in 
terms of bytes and that they represent -- It can not be a python type.

The only way to use arbitrary python types is a object array, which 
you've discovered, but then numpy doesn't know any thing about the 
objects, other than that they are python objects.

> So what would be the best way to use numpy arrays with "foreign" types
> (or is it possible at all) ?  I've designed the "real" Unit in C++ and
> exported it to python (via boost and shared pointers) and I would like
> to create array of such Units

If your type is a C++ class, then it may be possible, with some C 
hackary to get numpy to understand it, but you're getting beyong my 
depth here -- also I doubt that you'd get the full features like array 
math and all anyway -- that's all set up for basic numeric types.

Maybe others will have some idea, but I think you're pushing what numpy 
is capable of.

> (in fact, I also created an array-like
> class but I would prefer to use directly the real array interface to
> benefit from the great work of numpy instead of re-inventing the
> wheel). 

What operations do you expect to perform with these arrays of Units?


Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception


More information about the Numpy-discussion mailing list