More generic decimal example.

This commit is contained in:
Guido van Rossum 2005-05-18 14:24:27 +00:00
parent ca313eced9
commit a9a33511f4
1 changed files with 20 additions and 11 deletions

View File

@ -418,19 +418,28 @@ Examples
# so this must be outside the do-statement:
return +s
An alternative version of the generator saves the entire
context instead of just the precision attribute. This is more
robust, but also more expensive, making it perhaps the better
choice when several attributes are modified together:
9. Here's a more general Decimal-context-switching template:
@do_template
def with_extra_precision(places=2):
oldcontext = decimal.getcontext()
newcontext = oldcontext.copy()
newcontext.prec += places
decimal.setcontext(newcontext)
yield None
decimal.setcontext(oldcontext)
def with_decimal_context(newctx=None):
oldctx = decimal.getcontext()
if newctx is None:
newctx = oldctx.copy()
decimal.setcontext(newctx)
yield newctx
decimal.setcontext(oldctx)
Sample usage (adapted from the previous one):
def sin(x):
do with_decimal_context() as ctx:
ctx.prec += 2
# Rest of algorithm the same
return +s
(Nick Coghlan has proposed to add __enter__ and __exit__
methods to the decimal.Context class so that this example can
be simplified to "do decimal.getcontext() as ctx: ...".)
References