Reference implementation for the slice.indices method.
(slice, length)
| 25 | "None or have an __index__ method") |
| 26 | |
| 27 | def slice_indices(slice, length): |
| 28 | """ |
| 29 | Reference implementation for the slice.indices method. |
| 30 | |
| 31 | """ |
| 32 | # Compute step and length as integers. |
| 33 | length = operator.index(length) |
| 34 | step = 1 if slice.step is None else evaluate_slice_index(slice.step) |
| 35 | |
| 36 | # Raise ValueError for negative length or zero step. |
| 37 | if length < 0: |
| 38 | raise ValueError("length should not be negative") |
| 39 | if step == 0: |
| 40 | raise ValueError("slice step cannot be zero") |
| 41 | |
| 42 | # Find lower and upper bounds for start and stop. |
| 43 | lower = -1 if step < 0 else 0 |
| 44 | upper = length - 1 if step < 0 else length |
| 45 | |
| 46 | # Compute start. |
| 47 | if slice.start is None: |
| 48 | start = upper if step < 0 else lower |
| 49 | else: |
| 50 | start = evaluate_slice_index(slice.start) |
| 51 | start = max(start + length, lower) if start < 0 else min(start, upper) |
| 52 | |
| 53 | # Compute stop. |
| 54 | if slice.stop is None: |
| 55 | stop = lower if step < 0 else upper |
| 56 | else: |
| 57 | stop = evaluate_slice_index(slice.stop) |
| 58 | stop = max(stop + length, lower) if stop < 0 else min(stop, upper) |
| 59 | |
| 60 | return start, stop, step |
| 61 | |
| 62 | |
| 63 | # Class providing an __index__ method. Used for testing slice.indices. |
no test coverage detected
searching dependent graphs…