[Python-Dev] Example for PEP 343

Nick Coghlan ncoghlan at gmail.com
Wed May 18 10:51:51 CEST 2005


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   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.blogspot.com


More information about the Python-Dev mailing list