Built-in func to calculate negative indices??

Eddie and Babs kca17 at dial.pipex.com
Tue Apr 17 14:49:42 EDT 2001


Do we want a built-in function to calculate the absolute (ie, positive) 
values of negative subscript indices? For example:-

x = "python"

x[-2]        # = "o"; positive index = 4

pos = absIndex(len(x), -2)    # pos = 4

x[pos]        # = "o"



The "absIndex" function would have the semantics of the following Python
function:-

    def absIndex(index, size):
        if index >= 0:
            result = index
        elif index < 0:
            result = index + size

        if (result < 0) or (result >= size):
            return None        # ie, invalid result
        else:
            return result


It would be possible to constrain the return value to something between 0
and size - 1 within the function (using min and max), but this would make it
hard to spot index errors. You would, however, want to constrain the return
value when dealing with slices, so perhaps a separate "absSlice" would be
useful as well.

Of course it is very easy to implement these functions yourself in Python,
but I bet this same code is written over and over again by people
re-defining the subscript operators. Built-in functions might make the code
a bit more standard and self-documenting.

&.



More information about the Python-list mailing list