[Numpy-discussion] how to create an array of objects that are sequences?
Pearu Peterson
pearu at cens.ioc.ee
Fri Jan 4 14:03:29 EST 2008
On Fri, January 4, 2008 8:00 pm, Pearu Peterson wrote:
> On Fri, January 4, 2008 7:33 pm, Travis E. Oliphant wrote:
>> Pearu Peterson wrote:
>>> Hi,
>>>
>>> Say, one defines
>>>
>>> class A(tuple):
>>> def __repr__(self):
>>> return 'A(%s)' % (tuple.__repr__(self))
>>>
>>> and I'd like to create an array of A instances.
>>
>> The array function was designed a long time ago to inspect sequences and
>> flatten them.
>>
>> Arguably, there should be more intelligence when an "object" array is
>> requested, but there is ambiguity about what the "right" thing to do is.
>>
>> Thus, the current situation is that if you are creating object arrays,
>> the advice is to populate it after the fact.
>>
>> So, create an empty object array and insert the entries the way you want
>> them:
>>
>> a = np.empty(1,dtype=object)
>> a[0] = A((1,2))
> Meantime I was reading arrayobject.c and it seems that
> before objects are checked for being sequences, their
> __array_interface__ is accessed (eg in Array_FromSequence,
> discover_depth).
>
> Would this provide a solution if the class A would define
> a property __array_interface__? I just don't know what
> the data field should be for an object.
Ok, I found a partial solution:
class A(tuple):
def __repr__(self):
return 'A('+tuple.__repr__(self)+')'
@property
def __array_interface__(self):
import numpy
obj = numpy.empty(1,dtype=object)
obj[0] = self
return obj.__array_interface__.copy()
>>> from numpy import *
>>> array([A((1,2))])
array([[1, 2]], dtype=object)
but
>>> array(A((1,2)))
array([None], dtype=object)
Pearu
PS: sorry about previous mail, Send was pressed accidentaly.
More information about the NumPy-Discussion
mailing list