[Python-ideas] Hexadecimal floating literals

Steven D'Aprano steve at pearwood.info
Tue Sep 12 07:20:03 EDT 2017


On Mon, Sep 11, 2017 at 06:26:16PM -0600, Neil Schemenauer wrote:
> On 2017-09-12, Victor Stinner wrote:
> > Instead of modifying the Python grammar, the alternative is to enhance
> > float(str) to support it:
> > 
> > k = float("0x1.2492492492492p-3") # 1/7
> 
> Making it a different function from float() would avoid backwards
> compatibility issues. I.e. float() no longer returns errors on some
> inputs.

I don't think many people will care about backwards compatibility of 
errors. Intentionally calling float() in order to get an exception is 
not very common (apart from test suites). Its easier to use raise if 
you want a ValueError.

The only counter-example I can think of is beginner programmers who 
write something like:

num = float(input("Enter a number:"))

and are surprised when the "invalid" response "0x1.Fp2" is accepted. But 
then they've already got the same so-called problem with int accepting 
"invalid" strings like "0xDEADBEEF". So I stress that this is a problem 
in theory, not in practice.

> E.g.
> 
>     from math import hexfloat
>     k = hexfloat("0x1.2492492492492p-3")

I don't think that's necessary. float() is sufficient.

> I still think a literal syntax has merits.  The above cannot be
> optimized by the compiler as it doesn't know what hexfloat() refers
> to.  That in turn destroys constant folding peephole stuff that uses
> the literal.

Indeed. If there are use-cases for hexadecimal floats, then we should 
support both a literal 0x1.fp2 form and the float constructor.


-- 
Steve


More information about the Python-ideas mailing list