[Python-checkins] python/nondist/peps pep-0343.txt,1.14,1.15
gvanrossum@users.sourceforge.net
gvanrossum at users.sourceforge.net
Wed May 18 16:24:29 CEST 2005
Update of /cvsroot/python/python/nondist/peps
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv407
Modified Files:
pep-0343.txt
Log Message:
More generic decimal example.
Index: pep-0343.txt
===================================================================
RCS file: /cvsroot/python/python/nondist/peps/pep-0343.txt,v
retrieving revision 1.14
retrieving revision 1.15
diff -u -d -r1.14 -r1.15
--- pep-0343.txt 18 May 2005 03:58:29 -0000 1.14
+++ pep-0343.txt 18 May 2005 14:24:27 -0000 1.15
@@ -418,19 +418,28 @@
# 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
More information about the Python-checkins
mailing list