Search code examples
pythonpython-contextvars

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 possible
    context.run(callback, **cb_kw)

so that the callback and any code called from it would be able to access var via contextvars.copy_context(), but it looks like there is no API to do this, by design of contextvars.Context, and the only way to do this is to make a wrapper that sets the var via ContextVar.set() and calls the callback, and call that wrapper via context.run, is this the only way to implement this or am I missing something (maybe the contextvars design just requires doing some of this differently)?


Solution

  • Actually after checking a suggested related question I've found that this is as simple as

    context.run(var.set, 'var')
    

    This seems to be working as intended.