KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Having an issue with a custom iterator in that it will only iterate over the file once. I am calling seek(0) on the relevant file object in between iterations, but StopIteration is thrown on the first call to next() on the 2nd run through. I feel I am overlooking something obvious, but would appreciate some fresh eyes on this: class MappedIterator(object): """ Given an iterator of dicts or objects and a attribute mapping dict, will make the objects accessible via the desired interface. Currently it will only produce dictionaries with string values. Can be made to support actual objects later on. Somehow... :D """ def __init__(self, obj=None, mapping={}, *args, **kwargs): self._obj = obj self._mapping = mapping self.cnt = 0 def __iter__(self): return self def reset(self): self.cnt = 0 def next(self): try: try: item = self._obj.next() except AttributeError: item = self._obj[self.cnt] # If no mapping is provided, an empty object will be returned. mapped_obj = {} for mapped_attr in self._mapping: attr = mapped_attr.attribute new_attr = mapped_attr.mapped_name val = item.get(attr, '') val = str(val).strip() # get rid of whitespace # TODO: apply transformers... # This allows multi attribute mapping or grouping of multiple # attributes in to one. try: mapped_obj[new_attr] += val except KeyError: mapped_obj[new_attr] = val self.cnt += 1 return mapped_obj except (IndexError, StopIteration): self.reset() raise StopIteration class CSVMapper(MappedIterator): def __init__(self, rea
Tags (comma-separated)
Save Edits
Cancel