[issue15136] Decimal accepting Fraction

Zachary Ware report at bugs.python.org
Fri Aug 24 23:17:40 CEST 2012


Zachary Ware added the comment:

(Mark:)
>To the patch:  It looks fine, as far as it goes.  It needs tests.  

I remembered tests about 5 minutes after I submitted the initial patch :P. Here's a patch with some tests.  Note that I've never really done tests, so please let me know if there need to be more/less/different tests.

>To avoid the repetition of the division code, I'd suggest doing something like:
>
>    if context is None:
>        context = getcontext()

(Stefan:)
>If this goes in, I'd prefer that as_decimal() always uses a localcontext().
>As the patch stands, using as_decimal() pollutes the global context flags, 
>which can be quite unexpected

My first attempt was simply:

   def as_decimal(self, context=None):
       with localcontext(context):
           return Decimal(self.numerator) / Decimal(self.denominator)

Looking through decimal.py, it looks like that should work (and in fact it does in 3.2.3), but it seems that _decimal will only accept a context as the argument to localcontext(), not None.  Is that expected, or does that need an issue?

I didn't catch that the patch pollutes the global context flags, that is indeed ugly and unacceptable.

>If the function takes a context argument, it might be better to move it
>into the decimal module as Decimal.from_fraction(context).

Perhaps both?  Implement Decimal.from_fraction(f, context) to do the real work, and then Fraction.to_decimal() as:

   def to_decimal(self):
       return Decimal.from_fraction(self, None)

Those who really care about the context (Decimal users working with a Fraction) can get what they want, and those who don't (Fraction users who want to see a Decimal representation) don't have to bother, and fractions.py isn't polluted with stuff about contexts.

----------
Added file: http://bugs.python.org/file26989/issue15136_with_tests.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15136>
_______________________________________


More information about the Python-bugs-list mailing list