[Python-Dev] PEP 340 -- concept clarification

Nick Coghlan ncoghlan at gmail.com
Wed May 4 12:42:19 CEST 2005


Tim Peters wrote:
> I don't think anyone has mentioned this yet, so I will:  library
> writers using Decimal (or more generally HW 754 gimmicks) have a need
> to fiddle lots of thread-local state ("numeric context"), and must
> restore it no matter how the routine exits.  Like "boost precision to
> twice the user's value over the next 12 computations, then restore",
> and "no matter what happens here, restore the incoming value of the
> overflow-happened flag".  It's just another instance of temporarily
> taking over a shared resource, but I think it's worth mentioning that
> there are a lot of things "like that" in the world, and to which
> decorators don't really sanely apply.

To turn this example into PEP 340 based code:

     # A template to be provided by the decimal module
     # Context is thread-local, so there is no threading problem
     def in_context(context):
         old_context = getcontext()
         try:
             setcontext(context)
             yield
         finally:
             setcontext(old_context)

Used as follows:

     block decimal.in_context(Context(prec=12)):
         # Perform higher precision operations here

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net


More information about the Python-Dev mailing list