[Python-Dev] PEP 567 v2 (original) (raw)

Victor Stinner victor.stinner at gmail.com
Wed Jan 3 13:17:27 EST 2018


Do you have any use case for modifying a variable inside some context?

numpy, decimal, or some sort of tracing for http requests or async frameworks like asyncio do not need that.

Maybe I misunderstood how contextvars is supposed to be used. So let me give you an example.

I understand that decimal.py will declare its context variable like this:

contextvar = contextvars.ContextVar('decimal', default=Context(...))

Later if I would like to run an asyncio callback with a different decimal context, I would like to write:

cb_context = contextvars.copy_context() decimal_context = cb_context[decimal.contextvar].copy() decimal_context.prec = 100 cb_context[decimal.contextvar] = decimal_context # <--- HERE

loop.call_soon(func, context=cb_context)

The overall code would behaves as:

with localcontext() as ctx: ctx.prec = 100 loop.call_soon(func)

I don't know if the two code snippets have exactly the same behaviour.

I don't want to modify func() to run it with a different decimal context. So I would prefer to not have to call decimal.contextvar.set() or decimal.setcontext() in func().

But I would need contextvars.Context[var]=value to support such use case.

Decimal contexts are mutable, so modifying directly the decimal context object would impact all contexts which isn't my intent here.

Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20180103/ab0784a0/attachment.html>



More information about the Python-Dev mailing list