[Python-Dev] Mixing float and Decimal -- thread reboot

Stefan Krah stefan at bytereef.org
Tue Mar 23 13:09:59 CET 2010


Facundo Batista <facundobatista at gmail.com> wrote:
> On Fri, Mar 19, 2010 at 5:50 PM, Guido van Rossum <guido at python.org> wrote:
> 
> > As a downside, there is the worry that inadvertent mixing of Decimal
> > and float can compromise the correctness of programs in a way that is
> > hard to detect. But the anomalies above indicate that not fixing the
> 
> Decimal already has something that we can use in this case, and fits
> very nice here: Signals.

I like the simplicity of having a single signal (e.g. CoercionError), but
a strictness context flag could offer greater control for people who only
want pure decimal/integer operations.


For example:

  strictness 0: completely promiscuous behaviour

  strictness 1: current py3k behaviour

  strictness 2: current py3k behaviour + pure equality comparisons

  strictness 3: current py3k behaviour + pure equality comparisons +
                disallow NaN equality comparisons [1]


Just as an illustration, here is a quick and dirty diff using the
DefaultContext for simplicity:

Index: Lib/decimal.py
===================================================================
--- Lib/decimal.py      (revision 78352)
+++ Lib/decimal.py      (working copy)
@@ -3765,8 +3765,8 @@
     def __init__(self, prec=None, rounding=None,
                  traps=None, flags=None,
                  Emin=None, Emax=None,
-                 capitals=None, _clamp=0,
-                 _ignored_flags=None):
+                 capitals=None, strictness=1,
+                 _clamp=0, _ignored_flags=None):
         if flags is None:
             flags = []
         if _ignored_flags is None:
@@ -5785,7 +5785,9 @@
         return other
     if isinstance(other, int):
         return Decimal(other)
-    if raiseit:
+    if isinstance(other, float) and DefaultContext.strictness == 0:
+        return Decimal.from_float(other)
+    if raiseit or DefaultContext.strictness > 1:
         raise TypeError("Unable to convert %s to Decimal" % other)
     return NotImplemented
 
@@ -5800,7 +5802,8 @@
         flags=[],
         Emax=999999999,
         Emin=-999999999,
-        capitals=1
+        capitals=1,
+        strictness=1
 )



Stefan Krah


[1] See: http://mail.python.org/pipermail/python-dev/2009-November/093910.html,
         http://mail.python.org/pipermail/python-dev/2009-November/093952.html




More information about the Python-Dev mailing list