Skip to content

Instantly share code, notes, and snippets.

@bofm
Last active March 2, 2018 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bofm/df066df2176bbe69fc3e62e87e1afd1d to your computer and use it in GitHub Desktop.
Save bofm/df066df2176bbe69fc3e62e87e1afd1d to your computer and use it in GitHub Desktop.
It. A handy iterator with method chaining.
import itertools
import functools
class It:
"""A handy iterator with method chaining.
>>> It([1, 2, 3]).map(lambda x: x**2).filter(lambda x: x<5).chain_after('abc').apply(list)
['a', 'b', 'c', 1, 4]
"""
def __init__(self, iterable):
self._it = iter(iterable)
def __iter__(self):
return self._it
def reduce(self, fn, initializer=None):
if initializer is not None:
return functools.reduce(fn, self, initializer)
return functools.reduce(fn, self)
def map(self, *fns):
return It(fns).reduce(lambda it, fn: It(map(fn, it)), self)
def starmap(self, *fns):
return It(fns).reduce(lambda it, fn: It(itertools.starmap(fn, it)), self)
def filter(self, *fns):
return It(fns).reduce(lambda it, fn: It(filter(fn, it)), self)
def apply(self, *fns):
return It(fns).reduce(lambda it, fn: fn(it), self)
def apply_it(self, *fns):
return It(fns).reduce(lambda it, fn: It(fn(it)), self)
def chain(self, *iterables):
return It(itertools.chain(self, *iterables))
def chain_after(self, *iterables):
return It(itertools.chain(*iterables, self))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment