[PYTHON MATRIX-SIG] Slice expressions

tim@lassi.ece.uiuc.edu tim@lassi.ece.uiuc.edu
Thu, 17 Oct 1996 13:09:28 -0500


Konrad Hinsen <hinsen@ibs.ibs.fr> writes

Someone else says (sorry!):
>> I keep making this mistake...can someone put some documentation somewhere
>> that this index_expression _must_ be indexed with all three numbers to ensure
>> correct results, which is not the case with an actual array object. 
>> 
>> >>> index_expression[2:-2]                       
>> Traceback (innermost last):
>>   File "<stdin>", line 1, in ?
>> AttributeError: __len__
>> >>> index_expression[2:-2:1]
>> (slice(2, -2, 1),)

>Unfortunately there is no way to remove that restriction completely.
>I could make standard slices work for the case where both indices
>are specified (by implementing __getslice__ and a dummy __len__ that
>always returns zero), but you'd get a wrong answer if you leave out
>the second index (which would then be set to zero). You could
>obtain the correct result if __len__ could return None, but it must
>return a non-negative integer...

How about something like this (maxint should be safe because you can't
index past maxint anyway...):

class Index_expression_class:
    import sys
    maxint = sys.maxint

    def __getitem__(self, index):
	if type(index) == type(()):
	    return index
	else:
	    return (index,)

    def __len__(self):
	return self.maxint

    def __getslice__(self, start, stop):
	if stop == self.maxint:
	    stop = None
	return self[start:stop:1]

index_expression = Index_expression_class()



-- 
	-tim

+--------------------------------------------------------------------+
| Tim Hochberg               Ultrahigh Speed Digital Electronics Lab |
| tim@lassi.ece.uiuc.edu              University of Illinois         |
| http://dogbert.ece.uiuc.edu/~tim         (217) 333-6014            |
+--------------------------------------------------------------------+

=================
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
=================