Skip to content

Commit f26f9bf

Browse files
committed
eliminate _canonize_slice(), already exists as slice.indices()
1 parent a5a7c3c commit f26f9bf

File tree

1 file changed

+3
-33
lines changed

1 file changed

+3
-33
lines changed

unpythonic/collections.py

Lines changed: 3 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,7 @@ def in_slice(i, s, l=None):
616616
if isinstance(s, int):
617617
s = wrap(s)
618618
return i == s
619-
start, stop, step = _canonize_slice(s, l, wrap)
619+
start, stop, step = s.indices(l)
620620
cmp_start, cmp_end = (ge, lt) if step > 0 else (le, gt)
621621
at_or_after_start = cmp_start(i, start)
622622
before_stop = cmp_end(i, stop)
@@ -637,7 +637,7 @@ def index_in_slice(i, s, l=None):
637637
def _index_in_slice(i, s, l=None, _validate=True):
638638
if (not _validate) or in_slice(i, s, l):
639639
wrap = _make_negidx_converter(l)
640-
start, _, step = _canonize_slice(s, l, wrap)
640+
start, _, step = s.indices(l)
641641
return (wrap(i) - start) // step
642642

643643
def _make_negidx_converter(l): # l: length of sequence being indexed
@@ -647,7 +647,7 @@ def _make_negidx_converter(l): # l: length of sequence being indexed
647647
if l <= 0:
648648
raise ValueError("l must be an int >= 1, got {}".format(l))
649649
def apply_conversion(k):
650-
return k % l
650+
return slice(k, None, None).indices(l)[0]
651651
else:
652652
def apply_conversion(k):
653653
raise ValueError("Need l to interpret negative indices")
@@ -657,33 +657,3 @@ def convert(k):
657657
raise TypeError("k must be int, got {} with value {}".format(type(k), k))
658658
return apply_conversion(k) if k < 0 else k
659659
return convert
660-
661-
def _canonize_slice(s, l=None, w=None): # convert negatives, inject defaults.
662-
if not isinstance(s, slice):
663-
raise TypeError("s must be slice, got {} with value {}".format(type(s), s))
664-
665-
step = s.step if s.step is not None else +1 # no "s.step or +1"; someone may try step=0
666-
if step == 0:
667-
raise ValueError("slice step cannot be zero") # message copied from range(5)[0:4:0]
668-
669-
wrap = w or _make_negidx_converter(l)
670-
671-
start = wrap(s.start)
672-
if start is None:
673-
if step > 0:
674-
start = 0
675-
else:
676-
if l is None:
677-
raise ValueError("Need l to determine default start for step < 0")
678-
start = wrap(-1)
679-
680-
stop = wrap(s.stop)
681-
if stop is None:
682-
if step > 0:
683-
if l is None:
684-
raise ValueError("Need l to determine default stop for step > 0")
685-
stop = l
686-
else:
687-
stop = -1 # yes, really -1 to have index 0 inside the slice
688-
689-
return start, stop, step

0 commit comments

Comments
 (0)