[Python-Dev] Re: PEP 276 Simple Iterator for ints

Kragen Sitaker kragen at canonical.org
Tue Nov 20 12:10:39 CET 2001


"M.-A. Lemburg" <mal at lemburg.com> writes:
> Skip Montanaro wrote:
> >     * it should cause no backward compatibility issues (you can't put "..."
> >       in a list now, can you?  NumPy?)

You can't, no.

> Here's a slightly different approach which works now (= it doesn't
> even require a PEP :-):
> 
> With the new iterator support in Python, it should be 
> easily possible to write a module which exposes a singleton 
> infinite sequence called e.g. "integers". Then, using the slicing
> notion we already have in Python, you could write:
> 
> for i in integers[0,...,10]:
>     print i

I don't know what the new iterator support in Python is, but here's an
implementation of your suggested syntax in pure, backward-compatible
Python.  I really don't like naming the range inclusively, but that's
pretty much what this syntax requires.

# Iterate.py
# There's a PEP on better ways of writing integer sequences.  e.g. [0,
# .. 10] or [0, 2, .. 10].  This module gives you a variant of that
# syntax proposed by M.-A. Lemburg <mal at lemburg.com>.

class RangeClass:
    def __getitem__(self, slice):
        if type(slice) is not type((1, 2, 3)):
            raise TypeError, 'Range syntax %s wrong' % slice
        if len(slice) not in (3, 4) or slice[-2] is not Ellipsis:
            raise TypeError, 'Range syntax %s wrong' % slice
        start = slice[0]
        stop = slice[-1]
        if len(slice) == 3 and start <= stop:  step = 1
        elif len(slice) == 3 and start > stop: step = -1
        else:                                  step = slice[1] - start
        stop = stop + step
        return xrange(start, stop, step)

Range = RangeClass()





More information about the Python-list mailing list