Support hexadecimal floating-point literals

For the language syntax change, I think we should have a PEP. There needs to be a case made that the benefits are big enough to warrant syntax changes, and there are some choices to make that it would be good to discuss and record. It’s worth noting that something like 0x1.bp-4 is already valid at the syntax level (even though it’s not particularly useful, since there’s no bp attribute on integers).

>>> print(ast.dump(ast.parse("0x1.bp-4", mode="eval"), indent=4))
Expression(
    body=BinOp(
        left=Attribute(
            value=Constant(value=1),
            attr='bp',
            ctx=Load()),
        op=Sub(),
        right=Constant(value=4)))

If we start allowing . in 0x literals, then there’s also the question of whether something like 0x1.bit_length should remain legal syntax, or whether it should become illegal in the same way that 1.bit_length currently is. If it stays legal, what are the exact rules for determining when something like 0x1.abc is interpreted as a hex floating-point literal and when it’s interpreted as an attribute access on an integer?

For the formatting addition, I think a careful and complete description of the proposed new functionality in a GitHub issue would be enough, though again there are many details to be determined. BTW, why not presentation type x, with semantics similar to those of x for int? So the 0x prefix would be omitted unless using #x.

E.g., we already have:

>>> format(123, 'x')
'7b'
>>> format(123, '#x')
'0x7b'

and I’d propose something along the lines of

>>> format(123.4, 'x')
'1.ed9999999999ap+6'
>>> format(123.4, '#x')
'0x1.ed9999999999ap+6'
3 Likes