[Numpy-discussion] IndexExpression bug?

Robert Kern robert.kern at gmail.com
Fri Jun 5 18:12:02 EDT 2009


On Fri, Jun 5, 2009 at 16:14, Michael McNeil Forbes
<mforbes at physics.ubc.ca> wrote:
>  >>> np.array([0,1,2,3])[1:-1]
> array([1, 2])
>
> but
>
>  >>> np.array([0,1,2,3])[np.s_[1:-1]]
> array([1, 2, 3])
>  >>> np.array([0,1,2,3])[np.index_exp[1:-1]]
> array([1, 2, 3])
>
> Possible fix:
> class IndexExpression(object):
>     ...
>     def __len__(self):
>         return 0
>
> (Presently this returns sys.maxint)
>
> Does this break anything (I can't find any coverage tests)?  If not, I
> will submit a ticket.

I think that getting rid of __getslice__ and __len__ should work
better. I don't really understand what the logic was behind including
them in the first place, though. I might be missing something.

In [21]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:class IndexExpression(object):
:    """
:    A nicer way to build up index tuples for arrays.
:
:    For any index combination, including slicing and axis insertion,
:    'a[indices]' is the same as 'a[index_exp[indices]]' for any
:    array 'a'. However, 'index_exp[indices]' can be used anywhere
:    in Python code and returns a tuple of slice objects that can be
:    used in the construction of complex index expressions.
:    """
:
:    def __init__(self, maketuple):
:        self.maketuple = maketuple
:
:    def __getitem__(self, item):
:        if self.maketuple and type(item) is not tuple:
:            return (item,)
:        else:
:            return item
:--

In [22]: s2 = IndexExpression(False)

In [23]: s2[1:-1]
Out[23]: slice(1, -1, None)


-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list