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

Dave Kuhlman dkuhlman at cutter.rexx.com
Fri Dec 16 11:45:20 CST 2005

On Fri, Dec 16, 2005 at 10:40:55AM -0500, Alan G Isaac wrote:
> Is a special array interface necessary for scipy.array
> to access even simple sequence emulators?
> E.g., suppose I have
> >>> class simple:
> ...  def __init__(self,data):
> ...   self.data = data
> ...
> where it is enforced that data is a list,
> and to class this I add sequence emulation
> http://docs.python.org/ref/sequence-types.html
> Can someone please point me to a *minimal* example
> where I can then do
> x = simple([1,2,3])
> y = scipy.array(x)
> and end up with an array of the list values
> (just like when you do scipy.array([1,2,3])).

Perhaps you want something like this:

    class Simple:
        def __init__(self, data=None):
            if data == None:
                self.data = []
            elif type(data) != type([]):
                raise TypeError('data must be list')
                self.data = data
        def get_data(self):
            return self.data

    # This should work OK.
    def test1():
        x = Simple([1., 2., 3.,])
        y = scipy.array(x.get_data())
        print y

    # This should fail.
    def test2():
        x = Simple(1.0)
        y = scipy.array(x.get_data())
        print y


A few notes:

1. Note that the initializer for data is ``data=None`` and then we
   check for a None value and create an empty list rather than
   using an initializer like ``data=[]``.  If we were to use the
   second (``data=[]``), then our instances would share a single
   list, which we do not want. It's a somewhat tricky Python

2. Using properties or new style classes or something, there is a
   way to implement class Simple so that you can write ``x.data``
   to get the value instead of ``x.get_data()``.  But, you asked
   for simple, so that extension "is left as an excercise for the

3. About emulating a list.  To do that, just inherit from
   ``list``.  For example:

       class Simple(list):

   But, that made the solution *too* simple, and no fun at all.

Hope this helps.


Dave Kuhlman

More information about the SciPy-user mailing list