Working xrange() replacement proposal

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Chris King

    Working xrange() replacement proposal

    You guys are probably sick of these by now, but I've come up with an
    xrange() replacement that is actually (almost) implementable in pure Python.

    Some have previously suggested the form "for 0<=i<10:" to indicate iterating
    over a range of integers. This form works well in languages like Icon that
    can bind variables to all possible values, but Python doesn't (yet?) have
    this ability. Instead, I propose the syntax "for i in 0<=ints<10:". Though
    slightly more verbose, this form has the advantage of being more "Pythonic"
    in nature, binding i to each integer in the given range in turn.

    The other (major) advantage of this form is that it is implementable in pure
    Python: 'ints' is simply an object which represents the mathematical set of
    all integers. Its comparison functions return a similar object representing
    a portion of this set, and its __iter__ method returns an iterator over
    these integers.

    My implementation defines an 'intrange' class to represent these ranges,
    along with (previously proposed) Min and Max objects to represent the
    minimum and maximum integers. The intrange constructor accepts two values, a
    lower and upper bound (with the same meaning as those of xrange()).

    Two default intrange objects are defined, 'ints' and 'nats'. ints has
    upper and lower bounds of Max and Min, respectively, whereas nats has an
    upper bound of Max and a lower bound of 0.

    Limitations of this implementation:

    * Python doesn't allow overriding of the 'and' operator. Since chained
    comparisons are implemented using this operator, "for i in 0<=ints<10:"
    won't work (it will instead iterate over all integers less than 10). Two
    workarounds are to use either "(0<=ints)< 10" or "(0<=ints)&(int s<10)".
    Ideally intrange will be able to override "and" the same way it does "&".

    * 'Broken' ranges aren't supported; i.e. the ranges can't have any gaps in
    them. Whether or not this would be actually be useful (e.g. to emulate
    xrange(0,10,2)) is a question yet to be answered.

    The implementation is available at
    http://users.wpi.edu/~squirrel/temp/ints.py. Test it (in 2.3) with:

    from ints import ints,nats
    for i in (5<=ints)<10: print i
    print list(nats<10)
Working...