[Python-ideas] Float range class

Steven D'Aprano steve at pearwood.info
Fri Jan 9 04:13:50 CET 2015

On Thu, Jan 08, 2015 at 05:01:03PM +0100, Todd wrote:
> Currently, the range class is limited to integers.  However, in many
> applications, especially science and mathematics, ranges of float values
> are the norm.

Solving this problem for the standard library would be a good idea. The 
math module might be the best place for it, although that would require 
giving up the concept that it is a thin wrapper around your platform's C 
math routines. (I'm not sure just how much that idea still applies.)

I experimented with a few different ways of doing non-integral ranges:

This is probably the least correct way:

This recipe was more accurate than numpy's linspace, at least at the 

This recipe tries to combine them both:

If something like this makes it into the standard library, I think it is 
important that it isn't limited to just floats. If you pass it 
Fractions, or Decimals, it should return Fractions or Decimals, and not 
just convert everything to float.

> The first is to extend the existing range class so it can support floats or
> to use duck-typing to support any class that has the necessary methods.
> However, I would be worried about making such a fundamental change to such
> a core class, and either approach could hurt performance.

A very strong -1 on that.

> The second approach is to create a new class that handles floating-point
> ranges (perhaps called "frange") and/or a new class that handles duck-typed
> ranges (perhaps called "drange").  However, there isn't really a good place
> right now to put these as far as I can see.

No need to have two such classes. There should be one, and it should be 
polymorphic. If you want floats, pass it float arguments, if you want 
some other numeric type, pass it the type you want.

As for where it should live, the math module is the obvious place, but 
it is written in C (which is a barrier to adding new functionality, as 
opposed to Python modules).

Maybe it's time for the math.so library to be re-named to _math.so (or 
.dll on Windows), and a new math.py module created which ends with

from _math import *

That will allow new functionality to be written in Python first, and 
only written in C if necessary.

> The third approach is to create a new module for various range classes.
> For example there could be a float range, a datetime range, a decimal
> range, a duck-typed range, an abstract base class for making new range
> classes, etc.  However, this is a lot more work (although it wouldn't need
> to all be done at one time).



More information about the Python-ideas mailing list