Непонятно, как сделать self._history экземпляром IterPack не впадая в рекурсию?
Хочется возможности менять и его тоже.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pprint import pprint
class IterPack(object):
def __init__(self, iterable=None):
self._parent = None
self._iterable = None
self._history = [iterable]
def end(self, deep=1):
deep = abs(int(deep))
if deep <= (len(self._history) - 2):
res = self._history[deep]
else:
res = self._history[1]
return res
def __iter__(self):
if not self._iterable:
self._create_iterator()
return self._iterable.__iter__()
def __call__(self, param):
return self._history[-1](param)
def _create_iterator(self):
res = self._history[0]
for _lambda in self._history[1:]:
res = _lambda(res)
self._iterable = res
return self
def imap(self, _lambda):
res = lambda iterable: (_lambda(item) for item in iterable)
res = IterPack(res)
self._history.append(res)
return self
def ifilter(self, _lambda):
res = lambda iterable: (item for item in iterable if _lambda(item))
res = IterPack(res)
self._history.append(res)
return self
def irange(self, count):
self._history[-1] = xrange(count)
return self
def main():
a = IterPack(xrange(10))
a.imap(lambda x: x**2).imap(lambda x: x + 11).ifilter(lambda x: x%2!=0)
a.end(1).imap(lambda x: x*3)
for x in a: print x
for x in a._history: print x._history if hasattr(x, '_history') else x
b = IterPack()
b.irange(5)
for x in b: print x
if __name__ == '__main__':
main()