1 #!/usr/bin/env python 2 3 """ 4 Span-related objects. 5 6 Copyright (C) 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 class xrange(object): 23 24 "Implementation of xrange." 25 26 NO_END = object() 27 28 def __init__(self, start_or_end, end=NO_END, step=1): 29 30 "Initialise the xrange with the given 'start_or_end', 'end' and 'step'." 31 32 if end is xrange.NO_END: 33 self.start = 0 34 self.end = start_or_end 35 else: 36 self.start = start_or_end 37 self.end = end 38 39 self.step = step 40 self.current = self.start 41 self.limited = self.end is not xrange.NO_END 42 43 def __iter__(self): 44 45 "Return an iterator, currently self." 46 47 return self 48 49 def next(self): 50 51 "Return the next item or raise a StopIteration exception." 52 53 if self.limited: 54 if self.step < 0 and self.current <= self.end or self.step > 0 and self.current >= self.end: 55 raise StopIteration() 56 57 current = self.current 58 self.current += self.step 59 return current 60 61 class slice(xrange): 62 63 "Implementation of slice." 64 65 def __init__(self, start_or_end=None, end=xrange.NO_END, step=1): 66 67 "Initialise the slice with the given 'start_or_end', 'end' and 'step'." 68 69 xrange.__init__(self, start_or_end, end, step) 70 71 # vim: tabstop=4 expandtab shiftwidth=4