[Python-Dev] Example for PEP 343
Bob Ippolito
bob at redivi.com
Wed May 18 05:45:32 CEST 2005
On May 17, 2005, at 11:39 PM, Guido van Rossum wrote:
> [Raymond Hettinger]
>
>> 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
I have yet to use the decimal module much, so I may be completely off
here.. but why not write it like this:
@do_template
def with_decimal_context():
curctx = decimal.getcontext()
oldctx = curctx.copy()
yield curctx
decimal.setcontext(oldctx)
Saves a line and a context set :)
-bob
More information about the Python-Dev
mailing list