(original) (raw)
> 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