Guido van Rossum wrote: > 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
For the 'with' keyword, and the appropriate __enter__/__exit__ methods on decimal Contexts, this can be written: with decimal.getcontext() as ctx: ctx.prec += 2 # change other settings # algorithm goes here # Pre-with context guaranteed to be restored here The decimal.Context methods to make this work: def __enter__(self): current = getcontext() if current is self: self._saved_context = self.copy() else: self._saved_context = current setcontext(self) def __exit___(self, *exc_info): if self._saved_context is None: raise RuntimeError("No context saved") try: setcontext(self._saved_context) finally: self._saved_context = None Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.blogspot.com _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com