1.1 --- a/lib/__builtins__/sequence.py Wed Nov 23 15:47:45 2016 +0100
1.2 +++ b/lib/__builtins__/sequence.py Wed Nov 23 15:48:37 2016 +0100
1.3 @@ -3,7 +3,7 @@
1.4 """
1.5 Sequence operations.
1.6
1.7 -Copyright (C) 2015 Paul Boddie <paul@boddie.org.uk>
1.8 +Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk>
1.9
1.10 This program is free software; you can redistribute it and/or modify it under
1.11 the terms of the GNU General Public License as published by the Free Software
1.12 @@ -21,39 +21,60 @@
1.13
1.14 from native import _isinstance
1.15
1.16 -def _getitem(seq, index):
1.17 +class sequence:
1.18 +
1.19 + "A common base class for sequence types."
1.20
1.21 - "Return the item or slice specified by 'index'."
1.22 + def __getitem__(self, index):
1.23 +
1.24 + "Return the item or slice specified by 'index'."
1.25 +
1.26 + # Normalise any integer indexes, converting negative indexes to positive
1.27 + # ones.
1.28
1.29 - if _isinstance(index, int):
1.30 - index = _normalise_index(index, seq.__len__())
1.31 - return seq.__get_single_item__(index)
1.32 - elif _isinstance(index, slice):
1.33 - return seq.__getslice__(index.start, index.end)
1.34 - else:
1.35 - raise TypeError
1.36 + if _isinstance(index, int):
1.37 + index = _normalise_index(index, self.__len__())
1.38 + return self.__get_single_item__(index)
1.39 +
1.40 + # Handle slices separately.
1.41
1.42 -def _getslice(seq, start, end=None):
1.43 + elif _isinstance(index, slice):
1.44 + return self.__getslice__(index.start, index.end)
1.45 +
1.46 + # No other kinds of objects are supported as indexes.
1.47
1.48 - "Return a slice starting from 'start', with the optional 'end'."
1.49 + else:
1.50 + raise TypeError
1.51 +
1.52 + def __getslice__(self, start, end=None):
1.53
1.54 - length = seq.__len__()
1.55 + "Return a slice starting from 'start', with the optional 'end'."
1.56 +
1.57 + length = self.__len__()
1.58
1.59 - if start is None:
1.60 - start = 0
1.61 - else:
1.62 - start = _normalise_index(start, length)
1.63 + # Handle a null start as the first position, otherwise normalising any
1.64 + # start index.
1.65 +
1.66 + if start is None:
1.67 + start = 0
1.68 + else:
1.69 + start = _normalise_index(start, length)
1.70
1.71 - if end is None:
1.72 - end = length
1.73 - else:
1.74 - end = _normalise_index(end, length)
1.75 + # Handle a null end as the first position after the end of the sequence,
1.76 + # otherwise normalising any end index.
1.77 +
1.78 + if end is None:
1.79 + end = length
1.80 + else:
1.81 + end = _normalise_index(end, length)
1.82
1.83 - result = []
1.84 - while start < end:
1.85 - result.append(seq.__get_single_item__(start))
1.86 - start += 1
1.87 - return result
1.88 + result = []
1.89 +
1.90 + while start < end:
1.91 + result.append(self.__get_single_item__(start))
1.92 + start += 1
1.93 +
1.94 + return result
1.95
1.96 def _get_absolute_index(index, length):
1.97