[Python-Dev] Symmetry arguments for API expansion

Steven D'Aprano steve at pearwood.info
Wed Mar 21 00:34:29 EDT 2018


On Wed, Mar 21, 2018 at 12:32:11AM +0000, Chris Barker wrote:

> Could float et al. add an __index__ method that would return a ValueError
> if the value was not an integer?

That would allow us to write things like:

"abcdefgh"[5.0]

which is one of the things __index__ was invented to prevent.


> Of course, as pointed out earlier in this thread, an "exact" integer is
> probably not what you want with a float anyway....

Not always. For example, I might want a function factorial(x) which 
returns x! when x is an exact integer value, and gamma(x+1) when it is 
not. That is what the HP-48 series of calculators do.

(This is just an illustration.)

Another example is that pow() functions sometimes swap to an exact 
algorithm if the power is an int. There's no particular reason why 
x**n and x**n.0 ought to be different, but they are:

py> 123**10
792594609605189126649

py> 123**10.0
7.925946096051892e+20


On the other hand, some might argue that by passing 10.0 as the power, I 
am specifically requesting a float implementation and result. I don't 
wish to argue in favour of either position, but just to point out that 
it is sometimes reasonable to want to know whether a float represents an 
exact integer value or not.



-- 
Steve


More information about the Python-Dev mailing list