[Python-ideas] Python Float Update

Nick Coghlan ncoghlan at gmail.com
Tue Jun 2 02:08:37 CEST 2015


On 2 Jun 2015 08:44, "Andrew Barnert via Python-ideas"
<python-ideas at python.org> wrote:
>But the basic idea can be extracted out and Pythonified:
>
> The literal 1.23 no longer gives you a float, but a FloatLiteral, which is either a subclass of float, or an unrelated class that has a __float__ method. Doing any calculation on it gives you a float. But as long as you leave it alone as a FloatLiteral, it has its literal characters available for any function that wants to distinguish FloatLiteral from float, like the Decimal constructor.
>
> The problem that Python faces that Swift doesn't is that Python doesn't use static typing and implicit compile-time conversions. So in Python, you'd be passing around these larger values and doing the slow conversions at runtime. That may or may not be unacceptable; without actually building it and testing some realistic programs it's pretty hard to guess.

Joonas's suggestion of storing the original text representation passed
to the float constructor is at least a novel one - it's only the idea
of actual decimal literals that was ruled out in the past.

Aside from the practical implementation question, the main concern I
have with it is that we'd be trading the status quo for a situation
where "Decimal(1.3)" and "Decimal(13/10)" gave different answers.

It seems to me that a potentially better option might be to adjust the
implicit float->Decimal conversion in the Decimal constructor to use
the same algorithm as we now use for float.__repr__ [1], where we look
for the shortest decimal representation that gives the same answer
when rendered as a float. At the moment you have to indirect through
str() or repr() to get that behaviour:

 >>> from decimal import Decimal as D
 >>> 1.3
 1.3
 >>> D('1.3')
 Decimal('1.3')
 >>> D(1.3)
 Decimal('1.3000000000000000444089209850062616169452667236328125')
 >>> D(str(1.3))
 Decimal('1.3')

Cheers,
Nick.

[1] http://bugs.python.org/issue1580


More information about the Python-ideas mailing list