A wrapper class providing a rich-iterator API. From the user point of view, this class supersedes the builtin iter() function: like iter(), it is called as Iter(iterable) or (less frequently) as Iter(callable,sentinel) and it returns an iterator. The returned iterator, in additi
| 3 | from itertools import * |
| 4 | |
| 5 | class Iter(object): |
| 6 | '''A wrapper class providing a rich-iterator API. |
| 7 | |
| 8 | From the user point of view, this class supersedes the builtin iter() |
| 9 | function: like iter(), it is called as Iter(iterable) or (less frequently) |
| 10 | as Iter(callable,sentinel) and it returns an iterator. The returned |
| 11 | iterator, in addition to the basic iterator protocol, provides a rich API, |
| 12 | exposing as methods most functions of the itertools module. Notably, two |
| 13 | frequently used itertools functions, chain and islice, are conveniently |
| 14 | exposed as addition and slicing operators, respectively. |
| 15 | ''' |
| 16 | |
| 17 | def __init__(self, *args): self._it = iter(*args) |
| 18 | def __iter__(self): return self |
| 19 | def next(self): return self._it.next() |
| 20 | |
| 21 | def __add__(self, other): |
| 22 | if not isinstance(other,Iter): |
| 23 | raise TypeError('can only add Iter (not "%s") to Iter' % |
| 24 | other.__class__.__name__) |
| 25 | return Iter(chain(self._it, other._it)) |
| 26 | |
| 27 | def __mul__(self, num): return Iter(chain(*tee(self._it,num))) |
| 28 | __rmul__ = __mul__ |
| 29 | |
| 30 | def __getitem__(self, index): |
| 31 | if isinstance(index, int): |
| 32 | try: return islice(self._it, index, index+1).next() |
| 33 | except StopIteration: |
| 34 | raise IndexError('Index %d out of range' % index) |
| 35 | else: |
| 36 | start,stop,step = index.start, index.stop, index.step |
| 37 | if start is None: start = 0 |
| 38 | if step is None: step = 1 |
| 39 | return Iter(islice(self._it, start, stop, step)) |
| 40 | |
| 41 | def enumerate(self): return Iter(enumerate(self._it)) |
| 42 | def map(self, func): return Iter(imap(func,self)) |
| 43 | def zip(self, *others): return Iter(izip(self._it, *others)) |
| 44 | def filter(self, predicate): return Iter(ifilter(predicate,self._it)) |
| 45 | def filterfalse(self, predicate): return Iter(ifilterfalse(predicate,self._it)) |
| 46 | def cycle(self): return Iter(cycle(self._it)) |
| 47 | def takewhile(self, predicate): return Iter(takewhile(predicate, self._it)) |
| 48 | def dropwhile(self, predicate): return Iter(dropwhile(predicate, self._it)) |
| 49 | def groupby(self, keyfunc=None): return Iter(groupby(self._it, keyfunc)) |
| 50 | def copy(self): |
| 51 | self._it, new = tee(self._it) |
| 52 | return Iter(new) |
| 53 | |
| 54 | |
| 55 | def irange(*args): |
no outgoing calls
no test coverage detected