Sanitize a piece of python?

I use Python / ctypes to transfer the C library. One of the structures that I wrap is like a number vector, and I need the getitem () method of the corresponding Python class to support slicing. At the C level, I have a function known as slice:

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], all properties of the start, end and step of the slice object are set, but, for example, in the case of [-100:], the start property will be -100, and both properties of the end and step will be None , i.e. they must be sanitized before I can pass the integer values ​​to the slice_copy () C function. Now this sanitation is not very complicated, but I would think that the necessary functionality is already included in the Python source - or?

+4
source share
1 answer

There really is a function in the interface. slice objects have an indices() method that takes the length of a sequence as a parameter and returns the normalized start, stop, and step values ​​as a tuple.

+2
source

All Articles