1 #!/usr/bin/env python 2 3 """ 4 Iterator classes for indexing. 5 6 Copyright (C) 2011 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 ANY 14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 15 PARTICULAR PURPOSE. See the GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License along 18 with this program. If not, see <http://www.gnu.org/licenses/>. 19 """ 20 21 class Iterator: 22 23 "An iterator over records employing record accessors." 24 25 def __init__(self, accessor): 26 self.accessor = accessor 27 self.records = None 28 self.iterator = None 29 30 def set_records(self, records): 31 self.records = records 32 33 def __iter__(self): 34 self.iterator = iter(self.records) 35 return self 36 37 def next(self): 38 if self.iterator is None: 39 iter(self) 40 record = self.iterator.next() 41 return self.accessor.get_key(record), record 42 43 class StatefulIterator(Iterator): 44 45 "An iterator over records maintaining state." 46 47 def __init__(self, accessor, state): 48 Iterator.__init__(self, accessor) 49 self.state = state 50 51 def __iter__(self): 52 Iterator.__iter__(self) 53 self.state.reset() 54 return self 55 56 def next(self): 57 key, record = Iterator.next(self) 58 self.key = self.state.update(key) 59 return self.key, record 60 61 # vim: tabstop=4 expandtab shiftwidth=4