[Python-3000] Builtin iterator type
George Sakkis
gsakkis at rutgers.edu
Mon Nov 13 19:44:10 CET 2006
Following up on a recent c.l.py thread
(http://groups.google.com/group/comp.lang.python/browse_frm/thread/42818717b400bcd4/#),
I'd like to get an idea from python-dev folks on how much of a chance
is there for a builtin iterator type. Although there might be a slight
possibility to make this proposal backwards compatible, I am mainly
targetting Py3K, so compatibility is not a strict requirement.
The key points are:
1. Formalize the currently informal concept of iterator by changing
iter() from a builtin function to a type.
2. Augment this type with operators to implement operations currently
done explicitly by itertools.*.
3. Make this type a base for all other (existing and future) iterator
types, e.g. xrange and generator.
As a proof of concept, I provide below a sample implementation of how
I imagine this type to work (also posted in the original c.l.py.
thread):
from itertools import chain, tee, islice
import __builtin__
_builtin_iter = __builtin__.iter
class iter(object):
def __init__(self, iterable):
self._it = _builtin_iter(iterable)
def __iter__(self):
return self
def next(self):
return self._it.next()
def __getitem__(self, index):
if isinstance(index, int):
try: return islice(self._it, index, index+1).next()
except StopIteration:
raise IndexError('Index %d out of range' % index)
else:
start,stop,step = index.start, index.stop, index.step
if start is None: start = 0
if step is None: step = 1
return islice(self._it, start, stop, step)
def __add__(self, other):
return chain(self._it, other)
def __radd__(self,other):
return chain(other, self._it)
def __mul__(self, num):
return chain(*tee(self._it,num))
__rmul__ = __mul__
__builtin__.iter = iter
if __name__ == '__main__':
def irange(*args):
return iter(xrange(*args))
assert list(irange(5)[:3]) == range(5)[:3]
assert list(irange(5)[3:]) == range(5)[3:]
assert list(irange(5)[1:3]) == range(5)[1:3]
assert list(irange(5)[3:1]) == range(5)[3:1]
assert list(irange(5)[:]) == range(5)[:]
assert irange(5)[3] == range(5)[3]
s = range(5) + range(7,9)
assert list(irange(5) + irange(7,9)) == s
assert list(irange(5) + range(7,9)) == s
assert list(range(5) + irange(7,9)) == s
s = range(5) * 3
assert list(irange(5) * 3) == s
assert list(3 * irange(5)) == s
Thoughts, opinions, suggestions, objections, all welcome.
Regards,
George
More information about the Python-3000
mailing list