In the Python docs about Context Vars a Context::run method is described to enable executing a callable inside a context so changes that the callable perform to the context are contained inside the copied Context. Though what if you need to execute a coroutine? What are you supposed to do in order to achieve the same behavior?
In my case, what I wanted was something like this to handle a transactional context with possible nested transactions:
my_ctxvar = ContextVar("my_ctxvar")async def coro(func, transaction):token = my_ctxvar.set(transaction)r = await func()my_ctxvar.reset(token) # no real need for this, but why not eitherreturn rasync def foo():ctx = copy_context()# simplification to one case here: let's use the current transaction if there is oneif tx_owner := my_ctxvar not in ctx:tx = await create_transaction()else:tx = my_ctxvar.get()try:r = await ctx.run(coro) # not actually possibleif tx_owner:await tx.commit()except Exception as e:if tx_owner:await tx.rollback()raise from ereturn r