
[Raymond Hettinger]
The sin() example is correct. The precision is changed and restored in the current context.
I got that eventually. :-)
However, for a general purpose wrapper, it is preferable to make a context copy and then restore the context after the enclosed is run. That guards against the enclosed block making any unexpected context changes.
(Although if people get in the habit of using the provided wrappers and the do-statement, there won't be any unexpected changes.)
Also, since the wrapper is intended to work like a try/finally, it will make sure the context gets restored even if an exception is raised at some unexpected point in the middle of the computation.
Yes, that's the point of the do-statement. :- Anyway, perhaps we should provide this most general template: @do_template def with_decimal_context(): oldctx = decimal.getcontext() newctx = oldctx.copy() decimal.setcontext(newctx) yield newctx decimal.setcontext(oldctx) To be used like this: do with_decimal_context() as ctx: ctx.prec += 2 # change other settings # algorithm goes here -- --Guido van Rossum (home page: http://www.python.org/~guido/)