[Python-Dev] PEP 327: Decimal Data Type

Tim Peters tim.one at comcast.net
Mon Feb 2 19:28:55 EST 2004


[Michael Chermside]
> Imagine the following senario. I write some code which uses
> Decimal, and which sets the context to get the desired rounding
> behavior. Somewhere in my code I call a routine written by
> somebody else... perhaps some library code... which also does
> some calculations using Decimal.
>
> It would be a major pain if every time I called that library code
> it changed the context. I'd have to keep setting the context back
> after each and every call to the library code. A well-behaved
> library will not require me to go through these contortions, so
> after it does its work it will set the context back to what it was
> when I called it.

A well-designed library will restore only *part* of the context.  Some of
the state in numeric context controls arithmetic behavior, but other parts
are informational, telling you about exceptional conditions that occurred.
The user can choose to let exceptions be raised, or to suppress them (via
settings in numeric context).  In the latter case, knowledge that an
exceptional condition occurred is *recorded* in context.  A well-designed
library can't assume that the user wants exceptions to be raised, but must
inform a user running in "non-stop" mode that exceptional conditions
occurred.  Context is the way to do that; context holds both input and
output state.

It's difficult to write high-quality numeric libraries.  The facilities
offered by numeric context are a great aid in doing so, but it's still too
complex for simple gimmicks like "a stack" to help.  The burden is on code
that changes context to do so correctly from its caller's POV; if you call a
routine that makes a mess of your context, that's an error in the routine
you called.  In the same vein, if you write a routine that requires a
specific rounding mode, and don't arrange to force that rounding mode for
the duration of your routine, your routine is in error.  It's also in error
if it doesn't restore the rounding mode in effect when it was entered.  It's
also probably in error if it *does* blindly restore the settings of the
informational flags.




More information about the Python-Dev mailing list