Questions tagged [python-contextvars]

Contextvars are a concept similar to thread-local variables, intended to provide value isolation across co-routines executed in parallel in a Python async application. They are implemented in a module with the same name introduced in the stdlib in Python 3.7.0, specified in PEP-567.

Python-contextvars were first justified and introduced in PEP-550, which ended-up being rejected mainly for holding a too-ambitious scope. A narrowed down proposal came in PEP-567 that ended up implemented in Python 3.7.0. The idea is to be able to have cross-local scope values that can be shared across co-routines running in the same task under async-io, in the same way that thread-local-storage variables can provide value isolation for variable-names across different threads.

PEP 550 presents context vars as:

This PEP adds a new generic mechanism of ensuring consistent access to non-local state in the context of out-of-order execution, such as in Python generators and coroutines.

Thread-local storage, such as threading.local(), is inadequate for programs that execute concurrently in the same OS thread. This PEP proposes a solution to this problem.

34 questions
0
votes
1 answer

Can not access contextVariables in decorator

I have python decorator and I need pass contextVariable inside my decorator or as argument request_id in function Step 1: Declare contextVariables and methods _correlation_id_ctx_var: ContextVar[str] = ContextVar(CORRELATION_ID_CTX_KEY,…
Dmitriy_kzn
  • 518
  • 4
  • 16
0
votes
1 answer

Setting vars in a contextvars.Context directly

I want to call some function in a separate contextvars.Context, with some variables in this context set by the caller: def call_with_context(var, callback, **cb_kw): context = contextvars.copy_context() context.set('var', var) # not…
wRAR
  • 25,009
  • 4
  • 84
  • 97
0
votes
2 answers

Google CloudFunctions: ContextVar vs Global Var

Is there a difference between ContextVar and Global Var within Google Cloud Functions? I noticed that as Google tries to re-use GCF instances some global vars classes are reused from one GCF invocation to another and not init at the start of each…
0
votes
0 answers

How to translate commands without passing a context. (Discord Bot)

I'm coding a Discord bot. There you define your commands like @commands.command() async def hello(self, ctx): await ctx.send("Hello world!") This would create a command hello, which would send a message. Now I want to add translations to it.…
Spinne
  • 65
  • 1
  • 5
1 2
3