[Python-ideas] Float range class

Andrew Barnert abarnert at yahoo.com
Thu Jan 8 22:30:15 CET 2015

On Jan 8, 2015, at 10:40, Nathaniel Smith <njs at pobox.com> wrote:

> On Thu, Jan 8, 2015 at 5:58 PM, Todd <toddrjen at gmail.com> wrote:
>> On Thu, Jan 8, 2015 at 6:41 PM, Andrew Barnert <abarnert at yahoo.com> wrote:
>>> More generally: if an frange that works exactly like range but with floats
>>> (and rounding errors) is all you want, that's so trivial to write that it
>>> doesn't seem worth putting in the stdlib, unless the use case is very
>>> common.
>> In numerical computing the use-case is extremely common, in fact I would say
>> it practically universal.  Ideally it would be vectorized, but in practice
>> this is often not possible, requiring the use of loops.
> Can you give a more specific example? I believe your problem is real,
> but as a numerical programmer I can't think of an example of where
> I've ever wanted anything like this, so it's hard for me to visualize
> what exactly you're talking about.
> And is what you want just:
> class FRange:
>    def __init__(start, stop, step):
>        self.start = start
>        self.stop = stop
>        self.step = step
>    def __getitem__(self, i):
>        x = self.start + i * self.step
>        if x > self.stop:
>            raise IndexError

>    def __iter__(self):
>        i = 0
>        while True:
>            try:
>                yield self[i]
>            except IndexError:
>                return
>            i += 1

This isn't really necessary; any type whose __getitem__ takes int values from 0 up to some point and then raises IndexError beyond that is automatically iterable (and the built-in sequence iterator is basically a C-optimized version of what you just wrote).

While we're at it, you probably also want __len__, __contains__ (one more place for naive float rounding problems…), __reversed__, index, count, a __getitem__ that handles slices and negative values, and __hash__. All pretty simple to add. (In fact, if you inherit collections.abc.Sequence you'll get everything but __getitem__, __len__, and __hash__ for free, but you'd probably want to implement __contains__, index, and count anyway, because the default versions will be linear instead of constant.)

More information about the Python-ideas mailing list