Skip to content

Commit

Permalink
Resolve #6: use standard Python semantics for negative indices
Browse files Browse the repository at this point in the history
  • Loading branch information
Technologicat committed Aug 22, 2019
1 parent 16e683b commit b61da77
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
5 changes: 5 additions & 0 deletions unpythonic/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,11 @@ def convert(k):
if k is not None:
if not isinstance(k, int):
raise TypeError("k must be int, got {} with value {}".format(type(k), k))
# Almost standard semantics for negative indices. Usually -l < k < l,
# but here we must allow for conversion of the end position, for
# which the last valid value is one past the end.
if not -l <= k <= l:
raise IndexError("Should have -n <= k <= n, but n = len(args) = {}, and k = {}".format(l, k))
return apply_conversion(k) if k < 0 else k
return convert

Expand Down
6 changes: 5 additions & 1 deletion unpythonic/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ def rotated(*args, **kwargs):
n = len(args)
if not n:
raise TypeError("Expected at least one argument")
if not -n < k < n: # standard semantics for negative indices
raise IndexError("Should have -n < k < n, but n = len(args) = {}, and k = {}".format(n, k))
j = -k % n
rargs = args[-j:] + args[:-j]
return lazycall(f, *rargs, **kwargs)
Expand Down Expand Up @@ -577,7 +579,9 @@ def apply_f_to_kth_arg(*args):
n = len(args)
if not n:
raise TypeError("Expected at least one argument")
j = k % n # handle also negative values
if not -n < k < n: # standard semantics for negative indices
raise IndexError("Should have -n < k < n, but n = len(args) = {}, and k = {}".format(n, k))
j = k % n
m = j + 1
if n < m:
raise TypeError("Expected at least {:d} arguments, got {:d}".format(m, n))
Expand Down

0 comments on commit b61da77

Please sign in to comment.