[SciPy-user] sequence emulation -/-> array access?

Travis Oliphant oliphant.travis at ieee.org
Sat Dec 17 18:50:04 CST 2005

Alan G Isaac wrote:

>Is a special array interface necessary for scipy.array
>to access even simple sequence emulators?
No, it shoudn't be.   Internally, there is an if-else statement that 
checks if the object (in-order):

1. is an array (or subclass)
2. is an array-scalar
3. has the __array_struct__ interface
4. has the other __array_yyyy__ interface
5. has the __array__ method

If all the above fail, then either Array_FromSequence is called or 
Array_FromScalar is called.  To succeed in conversion your object must 
be able to be interpreted using the C-API PySequence_GetItem command. 

So, the question is:  What is needed on obj for PySequence_Check(obj) 
and PySequence_GetItem(obj) to succeed?   These are Python C-API calls.  
My impression has always been that classes that define at least the 
__len__ method and the __getitem__ method would succeed. 

So,  try this:

class myobj(object):
    def __init__(self, data):
        self.data = data
    def __len__(self):
        return len(self.data)
    def __getitem__(self, key):
        return self.data[key]

This seems to work for me...

a = myobj([1,2,3,4])
b = array(a)
print b


More information about the SciPy-user mailing list