4 ms·
Python's Decimal module (though not its floats, for some reason) has, IMO, a pretty good implementation of these features. https://docs.python.org/2/library/de
by ekimekim 12y ago
Python's Decimal module (though not its floats, for some reason) has, IMO, a pretty good implementation of these features.
https://docs.python.org/2/library/decimal.html#context-objects https://docs.python.org/2/library/decimal.html#context-objec...
Basically, it encapsulates attributes and status flags into a thread-local "context" which you get/set through normal function calls. There's also the helpful "with" syntax which allows you to say "run this code block (and anything it calls, etc) with this context instead of the current one, then restore the current one on exit".
A sibling comment talked about a sin() example where you want to use an explicit rounding mode for your calculations, then apply the global rounding mode to the result.
Under this paradigm it would look something like:
with MySpecialContext(settings, etc) as ctx:
calculations...
check status flags in ctx
get result
round result # this uses the parent context
return