Re: [Python-Dev] Adventures with Decimal

Guido writes:
It looks like if you pass in a context, the Decimal constructor still ignores that context
No, you just need to use the right syntax. The correct syntax for converting a string to a Decimal using a context object is to use the create_decimal() method of the context object:
import decimal decimal.getcontext().prec = 4 decimal.getcontext().create_decimal("1.234567890") Decimal("1.235")
Frankly, I have no idea WHAT purpose is served by passing a context to the decimal constructor... I didn't even realize it was allowed! -- Michael Chermside

[Michael Chermside]
Frankly, I have no idea WHAT purpose is served by passing a context to the decimal constructor... I didn't even realize it was allowed!
Quoth the docs for the Decimal constructor: """ The context precision does not affect how many digits are stored. That is determined exclusively by the number of digits in value. For example, "Decimal("3.00000")" records all five zeroes even if the context precision is only three. The purpose of the context argument is determining what to do if value is a malformed string. If the context traps InvalidOperation, an exception is raised; otherwise, the constructor returns a new Decimal with the value of NaN. """ Raymond

Michael Chermside wrote:
Frankly, I have no idea WHAT purpose is served by passing a context to the decimal constructor... I didn't even realize it was allowed!
As Tim pointed out, it's solely to control whether or not ConversionSyntax errors are exceptions or not: Py> decimal.Decimal("a") Traceback (most recent call last): File "<stdin>", line 1, in ? File "c:\python24\lib\decimal.py", line 571, in __new__ self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) File "c:\python24\lib\decimal.py", line 2266, in _raise_error raise error, explanation decimal.InvalidOperation Py> context = decimal.getcontext().copy() Py> context.traps[decimal.InvalidOperation] = False Py> decimal.Decimal("a", context) Decimal("NaN") I'm tempted to suggest deprecating the feature, and say if you want invalid strings to produce NaN, use the create_decimal() method of Context objects. That would mean the standard construction operation becomes genuinely context-free. Being able to supply a context, but then have it be mostly ignored is rather confusing. Doing this may also fractionally speed up Decimal creation from strings in the normal case, as the call to getcontext() could probably be omitted from the constructor. Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.blogspot.com
participants (3)
-
Michael Chermside
-
Nick Coghlan
-
Raymond Hettinger