ARTICLE AD BOX
I'm trying to access a variable value which is calculated at the beginning of the call stack. The value needs to be used deep down in a sub call, but the libraries being used don't allow any way to pass in the value as keyword argument or otherwise. I found the ContextVar as alternative and the way I understand it, one can set the variable and then access its value within the nested functions being called.
However, this doesn't seem to be working for me or I haven't fully understood the concept. This code snippet returns the default value None, instead of the string "new_value" which is what I hoped would be returned. The only way I could make this work was to use ctx_var in foo(), but that somehow defeats the purpose of not having access to the variable.
from contextvars import ContextVar ctx_var = ContextVar("bar") token = ctx_var.set("new_value") def foo(): bar = ContextVar("bar") bar_value = bar.get(None) print(bar_value) foo() ctx_var.reset(token)Any help would be great.
