[Python-Dev] PEP 550 v4

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Aug 30 08:55:43 EDT 2017


Yury Selivanov wrote:

> BTW we already have mechanisms to always propagate context to the
> caller -- just use threading.local() or a global variable.

But then you don't have a way to *not* propagate the
context change when you don't want to.

Here's my suggestion: Make an explicit distinction between
creating a new binding for a context var and updating an
existing one.

So instead of two API calls there would be three:

    contextvar.new(value) # Creates a new binding only
                          # visible to this frame and
                          # its callees

    contextvar.set(value) # Updates existing binding in
                          # context inherited from caller

    contextvar.get()      # Retrieves the current binding

If we assume an extension to the decimal module so
that decimal.localcontext is a context var, we can
now do this:

    async def foo():
       # Establish a new context for this task
       decimal.localcontext.new(decimal.Context())
       # Delegate changing the context
       await bar()
       # Do some calculations
       yield 17 * math.pi + 42

    async def bar():
       # Change context for caller
       decimal.localcontext.prec = 5

-- 
Greg


More information about the Python-Dev mailing list