""" A compatibility function 'iter' behaving like the built-in iter() function, but returning objects which also providing the interface of lists. It considers that all the elements that remain to be produced form a list, and this 'look-ahead' list can be indexed, sliced, and even mutated. Note that operations like slicing or concatenating return 'collect' objects, which behave more like lists in that iterating over them doesn't consume them. If you really want the consuming behavior, you have to call iter() again. """ from collect import collect class itercollect(collect): def __iter__(self): return self def next(self): try: result = self[0] except IndexError: raise StopIteration del self[0] return result builtin_iter = iter def iter(collection, *moreargs): if moreargs: collection = builtin_iter(collection, *moreargs) if not isinstance(collection, itercollect): collection = itercollect(collection) return collection if __name__ == '__main__': import sys def ansi_print(text, esc, file=None): if file is None: file = sys.stderr text = text.rstrip() if sys.platform != "win32" and file.isatty(): text = ('\x1b[%sm' % esc + text + '\x1b[0m') # ANSI color code "reset" file.write(text + '\n') n = 10 def f(): global n n -= 1 ansi_print(str(n), '31') return n it = iter(f, 0)