I am using Python/ctypes to wrap a C library. One of the structures I am wrapping resembles a numerical vector, and I would like the getitem() method of the corresponding Python class to support slices. At the C – level I have slice-aware function like this:
void * slice_copy( void * ptr , int index1 , int index2 , int step) {
...
}
My Python getitem() looks like this:
def __getitem__(self , index):
if isinstance( index , types.SliceType):
# Call slice_copy function ...
# Need values for arguments index1, index2 and step.
elif isinstance( index , types.IntType):
# Normal index lookup
else:
Raise TypeError("Index:%s has wrong type" % index)
If the slice literal looks like [1:100:10] the start,end and step properties of the slice object are all set, but e.g. in the case [-100:] the start property will be -100 and both the end and step properties will be None, i.e. they need to be sanitized before I can pass integer values to the C function slice_copy(). Now, this sanitizing is not very difficult, but I would have thought that the necessary functionality was already included in the Python source – or?
There is indeed a function in the interface.
sliceobjects have anindices()method that accepts the length of the sequence as parameter and returns the normalised start, stop and step values as a tuple.