On Thu, Mar 5, 2020 at 4:27 AM Steve Barnes <GadgetSteve@live.co.uk> wrote:

One of the lovely things about Python is that we have the capability to avoid issues such as the vagaries of the floating point type with libraries such as decimal and fractions. This is wonderous to me but comes with an issue that I suspect is limiting its usage. That issue is that you have to litter your code with constructors of those types, e.g.

 

```

a = 0.1

b = 0.2

c = 0.3

a + b == c # This doesn’t work but it is easy to forget why

```

vs:

```

from decimal import *  # I know why this is bad but it comes straight from the examples

a = Decimal("0.1")  # Needs to be a string to avoid being temporarily a float

b = Decimal("0.2")  # Ditto

c = Decimal("0.3")  # Ditto

a + b == c  # Magic this works!

```

 

While this works it is not very friendly to users and there will often be cases where people forget to quote the values, etc. and there are similar issues with using the fractions library and I am sure with others. I suspect that this is why the decimals library, and some others, is not used as widely as it possibly should be.

 

Wouldn’t it be possible to have something along the lines of:

 

```

from decimal import TreatFloatsAsDecimal

@TreatFloatsAsDecimal

a = 0.1  # These are all now decimals

b = 0.2

c = 0.3

a + b == c # This now works

``




If you were going to do this you would probably need something like a context manager to control the scope, such as:

with TreatFloatsAsDecimal:
    a = 0.1  # decimal
    b = 0.2  # decimal
    c = 0.3  # decimal

d = 0.3  # float

I have been interested in something like this in the context of numpy arrays, but I am not sure even that would even be possible under how the python language works, and if it was I figured it was too complicated to be worthwhile.